| FAQ Index - Search - Recent Changes - Everything - Add entry |
5.4. How do I catch right-click, middle-click and double-click on my widget?
All widgets that receive events (see FAQ 3.3) can attach to button_press_event to 'listen' for button presses. It may be necessary to alter the event mask for certain widgets (gtk.Window, for instance):
window.add_events(gtk.gdk.BUTTON_PRESS_MASK)You can easily capture a specific button press pattern by checking event.button and comparing event.type with the constants defined in gtk.gdk for multiple button presses. To do this, connect a handler like this one to "button_press_event" on your widget:
def button_clicked(widget, event):
# which button was clicked?
if event.button == 1:
print "left click"
elif event.button == 2:
print "middle click"
elif event.button == 3:
print "right click"
# was it a multiple click?
if event.type == gtk.gdk.BUTTON_PRESS:
print "single click"
elif event.type == gtk.gdk._2BUTTON_PRESS:
print "double click"
elif event.type == gtk.gdk._3BUTTON_PRESS:
print "triple click. ouch, you hurt your user."
Note that it seems that, at least in PyGTK 0.6.x (confirm for 2.x), spawning a modal dialog when handling a double-click event causes a strange focus bug. I've experienced this personally, but this message confirms the problem:
[mail.gnome.org]
To work around it, I changed the modality using idle_add(win.set_modal, 1) before calling mainloop, but it's a very ugly fix.
