How to Get Key Presses in Python
By Jaime Avelar
Learning how to capture each key pressed on your keyboard using Python is one way to keep a record of information you type on your computer. Python is a computer programming language that can be used to easily capture keys programmatically. One advantage about a Python program is that it runs in multiple operating systems, such as Linux\Unix, Max OS X and Windows, according to Python.com. In Python the "keysym" property is used to detect the key pressed; the “Char()” property is used to retrieve the key.
Step 1
Launch IDLE (Python GUI), click the “File” menu and click “New Window” to launch a new window. Press “Ctrl” and “S” to launch the “Save As” dialog window. Type “getKeyPressed” next to “File name:" and click “Save.”
Step 2
Add the following code to import the “Tkinter” namespace to your project:
import Tkinter as tk
Step 3
Copy and paste the following code to get each key pressed.
def keypress(event): if event.keysym == 'Escape': mainRoot.destroy() keyPressed = event.char print "You pressed: " + keyPressed
Step 4
Add the following code to print the key pressed using the command prompt window:
mainRoot = tk.Tk() print "Press a key (Escape key to exit):" mainRoot.bind_all('
Step 5
Click the “Windows” start button and type “Cmd” in the “search programs and files” text box. Press “Enter” to open the command prompt window. Navigate to “C:\Python
References
Writer Bio
Jaime Avelar is a professional writer whose programming articles appear on various websites. He has been a software programmer since 2000. Avelar holds a Master of Science in information systems from the University of Texas at Arlington.