2013-01-12 159 views
3

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

回答

9

有不擁有自己的性能方面的原因一個X窗口,因爲他們大多是裝飾性的一般不需要處理X事件信號的某些部件。你可以找到一個完整的列表here

在這些情況下,推薦使用GtkEventBox來包裝無窗口小部件(EventBox是專門爲該目標構建的)。

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