FAQ Index - Search - Recent Changes - Everything - Add entry

<< Previous Entry | FAQ Entry 5.5 | Next Entry >>

5.5. How do I capture keypresses, and how do I perform a certain action depending on the key pressed?

You can capture the generic key_press_event in any widget that has the key press mask set or in the top level window that the widget is displayed in. Key events are sent to the top level window before they are sent to the child widget that currently is the focus widget. As a basic example:

 def on_key_press_event(widget, event):
   keyname = gtk.gdk.keyval_name(event.keyval)
   print "Key %s (%d) was pressed" % (keyname, event.keyval)

 w = gtk.Window()
 w.connect('key_press_event', on_key_press_event)
If you want to block a specific key from being catched by a widget, just return True in the key_press_event signal handler.

Which will print out the key pressed for that window. To use a specific handler for each key pressed, you can set something up like this:

  def on_key_press(self, widget, event):
    keyname = gtk.gdk.keyval_name(event.keyval)
    func = getattr(self, 'keypress_' + keyname, None)
    if func:
      return func()

  def keypress_A(self):
    print "A was pressed!"

  def keypress_B(self):
    print "B was pressed!"
To capture Control, Alt and Shift combinations, you need to use the gtk.gdk symbols CONTROL_MASK, MOD[1-5]_MASK and SHIFT_MASK and do a binary AND to event.state:

 def on_key_press(widget, event):
   keyname = gtk.gdk.keyval_name(event.keyval)
   print "Key %s (%d) was pressed" % (keyname, event.keyval)
   if event.state & gtk.gdk.CONTROL_MASK:
     print "Control was being held down"
   if event.state & gtk.gdk.MOD1_MASK:
     print "Alt was being held down"
   if event.state & gtk.gdk.SHIFT_MASK:
     print "Shift was being held down"

 w = gtk.Window()
 w.connect('key_press_event', on_key_press)

PyGTK FAQ Wizard | PyGTK Homepage | Feedback to faq at pygtk.org