Gtk:如何检测 EventBox 上的鼠标位置?

Gtk: How to detect the mouse position over EventBox?

我一直在尝试在 Python 中编写简单的 CAD 应用程序。我正在修补 pyglet,得到了一些结果:,但我决定切换回 Gtk,结果碰壁了:

我无法获取 EventBox 上的鼠标指针位置(对于 pyglet,它是图片中 window 应用程序左下角的标签)。为它设计什么信号?或者我应该使用其他方法?

我将不胜感激任何信息或资源。提前致谢。

Question: How to detect the mouse position over EventBox?

  • how-to-capture-event-on-event-box-to-detect-mouse-movement-in-gtk
  • Gtk.EventBox

    The Gtk.EventBox widget is a subclass of Gtk.Bin which also has its own window. It is useful since it allows you to catch events for widgets which do not have their own window.

  • Gtk.Widget.add_events(events)

    Adds the events in the bitfield events to the event mask for self.

  • Gdk.EventMask

    A set of bit-flags to indicate which events a window is to receive.

应该是Gtk.EventBox拿到了flag,不是window!

box = Gtk.EventBox()
box.connect("motion-notify-event", self.on_mouse_move)
box.add_events(Gdk.EventMask.POINTER_MOTION_MASK)

stovfl 的帮助下,解决方案得以实现。 应用程序 由绘图区、框架、事件框和标签组成,用于显示鼠标指针坐标。绘图区添加到框,框添加到框架,框架添加到网格。

from gi.repository import Gtk
from gi.repository import Gdk
# (...)
    box = Gtk.EventBox()
    box.add_events(Gdk.EventMask.POINTER_MOTION_MASK)  # 1
    box.connect("button-press-event", self.on_click)
    box.connect("motion-notify-event", self.on_mouse_move)  # 2
    self.canvas = Gtk.DrawingArea()
    self.canvas.connect("draw", self.on_draw)
    self.canvas.set_size_request(800, 600)
    box.add(self.canvas)
    grid = Gtk.Grid()
    frame = Gtk.Frame()
    frame.set_label("KHAD")
    frame.add(box)
    grid.attach(frame, 0, 1, 1, 1)
    self.add(grid)
    # (...)
    self.locationLabel = Gtk.Label("X,Y")
    self.locationLabel.set_alignment(0, 0)
    grid.attach(self.locationLabel, 0, 2, 1, 1)

解决方案是:

  1. POINTER_MOTION_MASK添加到事件框:box.add_events(Gdk.EventMask.POINTER_MOTION_MASK)
  2. 用方法连接框的 motion-notify-event,该方法读取并更新标签(左下角;它与 self.locationLabel.set_alignment(0, 0) 对齐)。