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

<< Previous Entry | FAQ Entry 3.2 | Next Entry >>

3.2. How do I detect that a mouse or keyboard event has been triggered?

Q: I'm interested in writing a program similar to an x screen saver. It watches for user keystrokes, every time it receives one, it restarts a timer. How can I detect whenever the user hits a key or moves the mouse?

The correct way is to hook to some of the basic event signals and then act upon receiving them. The signals you want to look for are:

 - mouse motion
 - key presses
 - button presses
However, many widgets don't have their event masks properly set, so they will ignore these events. The following example shows how it should be done for a GtkWindow, adding the necessary event masks, and then hooking to the signals. Note that you would have to alter the wakeup function to handle the timer operations you would need for a screensaver.

 def wakeup(widget, event):
     print "Event number %d woke me up" % event.type

 w = gtk.Window()

 w.add_events(gtk.gdk.KEY_PRESS_MASK |
              gtk.gdk.POINTER_MOTION_MASK |
              gtk.gdk.BUTTON_PRESS_MASK | 
              gtk.gdk.SCROLL_MASK)

 w.connect("motion-notify-event", wakeup)
 w.connect("key-press-event", wakeup)
 w.connect("button-press-event", wakeup)
 w.connect("scroll-event", wakeup)

 w.show()

 gtk.main()
Note that mouse "scroll-wheel" events are implemented as button clicks in the Xorg X11R6 server (button 4 for scroll up, button 5 for scroll down).

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