How to Get Key Presses in Pythonby 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.
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.”
Add the following code to import the “Tkinter” namespace to your project: import Tkinter as tk
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
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('
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
- Hemera Technologies/AbleStock.com/Getty Images