How to Get Key Presses in Python

By Jaime Avelar

A display key pressed is revealed in Python.
i Hemera Technologies/AbleStock.com/Getty Images

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('', keypress) mainRoot.withdraw() mainRoot.mainloop()

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\” and type “python getKeyPressed.” Press “Enter” to run your program. Start typing using your keyboard to display each key pressed to the command prompt window.

×