Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect key press combination in Linux with Python?

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()
like image 438
Ben L Avatar asked Feb 05 '09 13:02

Ben L


People also ask

How does Python detect Press button?

To detect keypress, we will use the is_pressed() function defined in the keyboard module. The is_pressed() takes a character as input and returns True if the key with the same character is pressed on the keyboard.

Can Python simulate keypress?

This demonstrates how to press keys with Python. Using pynput we are able to simulate key presses into any window. This will show you how to press and release a key, type special keys and type a sentence.

How do I know which key is pressed on my keyboard?

The Windows on-screen keyboard is a program included in Windows that shows an on-screen keyboard to test modifier keys and other special keys. For example, when pressing the Alt , Ctrl , or Shift key, the On-Screen Keyboard highlights the keys as pressed.


1 Answers

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...

like image 191
Ulf Avatar answered Sep 21 '22 15:09

Ulf