How would I go about detecting keystrokes on the keyboard?

Turns out Pygame isnt just for games. I wrote this script using it and it does exactly what I wanted it to do!

You can use the Tkinter GUI toolkit too:

# KeyLogger.py
# show a character key when pressed without using Enter key
# hide the Tkinter GUI window, only console shows

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()

Thanks for the reply. The program I wrote with pygame did certain actions when keys were pressed. When you held control and g down, google opened up. Can you do the same thing with Tkinter?

However, pyHook and pythoncom work only on Windows systems. Not too bad, since most computers in this world are using Windows. Tkinter is more cross-platform for the few odd folks that user other OS.

The code does not work on my Mac. If I comment out the withdrawing of the root window then it works fine as long as I make the root window focused. Tested for Python 3.2.2 and Python 2.7.2.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.