标签不会触发鼠标事件

时间:2013-01-12 22:58:52

标签: gtk pygtk

在pygtk引用中,它指出每个Gtk.Widget都有事件enter-event-notify,但是使用我的测试代码,事件永远不会为Label小部件触发(与其他人一起工作)。

我应该做些什么不同的事情吗?

import pygtk
pygtk.require('2.0')
import gtk

class LabelTest:

    def delete_event(self, widget, event, data=None):
        return False

    def destroy(self, widget, data=None):
        gtk.main_quit()

    def __init__(self):
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)

        self.window.connect("delete_event", self.delete_event)
        self.window.connect("destroy", self.destroy)
        self.window.set_border_width(10)

        self.label = gtk.Label("A label")

        # question section
        def labelMouseOver(w, data=None):
          print "mouse over"

        self.label.connect('enter-notify-event', labelMouseOver, None)
        # /question section

        self.window.add(self.label)
        self.label.show()
        self.window.show()

    def main(self):
        gtk.main()

if __name__ == "__main__":
    test = LabelTest()
    test.main()

2 个答案:

答案 0 :(得分:9)

由于性能原因,某些小部件没有自己的X窗口,因为它们大多是装饰性的,通常不需要处理X事件信号。您可以找到完整列表here

在这些情况下,建议使用GtkEventBox来包装无窗口小部件(事件框是专门为此目标构建的)。

答案 1 :(得分:3)

好的我已经得到了解决方案,它和以上一样:Enter-Notify-Event Signal not working on gtk.ToolButton。由于一些非显而易见的原因,某些小部件无法自行响应信号,并且需要在它们周围添加一个额外的框。我已经以我将要做的方式重写了代码示例 - 即使用导入来获取更新的GTK 3.0,并通过派生Gtk.Window来实现更面向对象的样式。另外,人们可能更喜欢实例方法而不是嵌套方法。

from gi.repository import Gtk

class Foo (Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self)
        self.connect("destroy", Gtk.main_quit)
        self.set_border_width(50)
        box = Gtk.EventBox()
        label = Gtk.Label("Test")   
        box.add(label)
        box.connect("enter-notify-event", self.on_mouse)
        self.add(box)
        self.show_all()

    def on_mouse(self, widget, data=None):
        print widget, data

    def main(self):
        Gtk.main()

if __name__ == "__main__":
    Foo().main()