How to Check for Keypress in Python

How to Check for Keypress in Python thumbnail
A Python application can capture key presses as soon as they happen.

Most input primitives and derived classes in the Python programming language deal with console input by requiring that the user press "Enter" to get the input relayed to the code. However, that is not acceptable in applications (e.g., games or other interactive programs) where responses have to be nimble and immediate; the requirement of pressing "Enter" after each command becomes overly cumbersome in such scenarios. You can write Python code that reads each key as soon as it gets pressed on the keyboard.

Instructions

    • 1

      Include this line at the beginning of your Python code:

      import Tkinter as tk

    • 2

      Create a function that processes each keypress event as it happens:

      def handleKeypress(event):

      pressedKey = event.char

      print pressedKey

      Replace the "print pressedKey" line with whatever processing your program needs to apply to the keypress read from the keyboard.

    • 3

      Establish the Tkinter bindings that will allow your program to process keypresses. The following sample code, added to the initialization section of your Python program, has that purpose:

      mainHandle = tk.Tk()

      mainHandle.bind_all('<Key>', handleKeypress)

      mainHandle.withdraw()

      mainHandle.mainloop()

      Every single keypress (hence the call to the "bind_all()" method) will cause the "handleKeypress()" function to be called.

Related Searches:

References

  • Photo Credit Jupiterimages/Photos.com/Getty Images

Comments

Related Ads

Featured