views:

45

answers:

1

Hello people, consider the following python code:

import gtk

class MainWindow():
    def __init__(self):
        self.window = gtk.Window()
        self.window.show()

if __name__ == "__main__":
    main = MainWindow()
    gtk.main()

I'd need to catch clicks anywhere inside this gtk.Window(). I haven't found any suitable event (I also tried button-press-event, but it doesn't work), what am I missing?

Thank you!

+1  A: 

You can pack a gtk.EventBox into the window. In general, whenever you have troubles catching events, check if gtk.EventBox solves them.

import gtk

class MainWindow():
    def __init__(self):
        self.window = gtk.Window()
        self.box = gtk.EventBox ()
        self.window.add (self.box)
        self.box.add (gtk.Label ('some text'))
        self.window.show_all()

        import sys
        self.box.connect ('button-press-event',
                          lambda widget, event:
                              sys.stdout.write ('%s // %s\n' % (widget, event)))

if __name__ == "__main__":
    main = MainWindow()
    gtk.main()

Note, however, that event propagation upwards the widget hierarchy will stop if a widget handles event itself. For instance, a parent of gtk.Button won't receive click events from it.

doublep
Thank you doublep; do you know of something able to catch also events handled singularly by children widgets?
David Paleino
@David Paleino: You could try using `gobject.add_emission_hook` and in your callback re-emit caught signal on parent widget — or on a toplevel right away if that's all you need. No idea if this will work, but that's what I'd try.
doublep
Thank you, I'll try! :)
David Paleino