Detect key press combination in Linux with Python?

Ben L picture Ben L · Feb 5, 2009 · Viewed 7.2k times · Source

I'm trying to capture key presses so that when a given combination is pressed I trigger an event.

I've searched around for tips on how to get started and the simplest code snippet I can find is in Python - I grabbed the code below for it from here. However, when I run this from a terminal and hit some keys, after the "Press a key..." statement nothing happens.

Am I being stupid? Can anyone explain why nothing happens, or suggest a better way of achieving this on Linux (any language considered!)?

import Tkinter as tk

def key(event):
    if event.keysym == 'Escape':
        root.destroy()
    print event.char

root = tk.Tk()
print "Press a key (Escape key to exit):"
root.bind_all('<Key>', key)
# don't show the tk window
root.withdraw()
root.mainloop()

Answer

Ulf picture Ulf · Feb 5, 2009

Tk does not seem to get it if you do not display the window. Try:

import Tkinter as tk

def key(event):
    if event.keysym == 'Escape':
        root.destroy()
    print event.char

root = tk.Tk()
print "Press a key (Escape key to exit):"
root.bind_all('<Key>', key)
# don't show the tk window
# root.withdraw()
root.mainloop()

works for me...