首页 > 解决方案 > 是否可以在 textview gtk 中获取光标坐标

问题描述

我正在使用 Gtk 使用 Pythons 开发一个应用程序gi.repository。我想知道是否可以在文本视图中移动光标时获取光标相对于屏幕的坐标。

例如,它返回光标的 x1, x2, y1, y2。

标签: pythongtk

解决方案


是的,有可能。只需绑定TextViewto "event",并在处理函数中检查事件类型是否为Gdk.EventType.MOTION_NOTIFY.

import gi

gi.require_version("Gdk", "3.0")
gi.require_version("Gtk", "3.0")
from gi.repository import Gdk, Gtk

win = Gtk.Window()

def on_event(widget, event):
    # Check if the event is a mouse movement
    if event.type == Gdk.EventType.MOTION_NOTIFY:
        print(event.x, event.y) # Print the mouse's position in the window

t = Gtk.TextView()
t.connect("event", on_event)
win.add(t)

win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()

推荐阅读