Label does not trigger mouse event

2019-02-24 21:58发布

问题:

In the pygtk reference it states that every Gtk.Widget has the event enter-event-notify, but with my test code that event is never fired for the Label widget (with others it has worked).

Is there something I should do differently?

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()

回答1:

There are certain widgets that don't own a X-window of their own for performance reasons ,since they are mostly decorative an generally don't need to handle X event signals. You can find a complete list here.

In those cases, a GtkEventBox is recommended to wrap the windowless widget with(the EventBox was build with that objective specifically).



回答2:

OK I've got the solution, it's the same as over here: Enter-Notify-Event Signal not working on gtk.ToolButton. For some non-obvious reason some widgets can't respond to signals on their own and need an extra box around them. I've rewritten the code example in a way I would have done it - namely using imports for more recent GTK 3.0 and a more object oriented style by deriving from Gtk.Window. Also one might prefer instance methods instead of nested ones.

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()


标签: gtk pygtk