Detect key input in Python Detect key input in Python tkinter tkinter

Detect key input in Python


You could make a little Tkinter app:

import Tkinter as tkdef onKeyPress(event):    text.insert('end', 'You pressed %s\n' % (event.char, ))root = tk.Tk()root.geometry('300x200')text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12))text.pack()root.bind('<KeyPress>', onKeyPress)root.mainloop()


Use Tkinterthere are a ton of tutorials online for this.basically, you can create events. Here is a link to a great site!This makes it easy to capture clicks.Also, if you are trying to make a game, Tkinter also has a GUI.Although, I wouldn't recommend Python for games at all, it could be a fun experiment.Good Luck!


Key input is a predefined event. You can catch events by attaching event_sequence(s) to event_handle(s) by using one or multiple of the existing binding methods(bind, bind_class, tag_bind, bind_all). In order to do that:

  1. define an event_handle method
  2. pick an event(event_sequence) that fits your case from an events list

When an event happens, all of those binding methods implicitly calls the event_handle method while passing an Event object, which includes information about specifics of the event that happened, as the argument.

In order to detect the key input, one could first catch all the '<KeyPress>' or '<KeyRelease>' events and then find out the particular key used by making use of event.keysym attribute.

Below is an example using bind to catch both '<KeyPress>' and '<KeyRelease>' events on a particular widget(root):

try:                        # In order to be able to import tkinter for    import tkinter as tk    # either in python 2 or in python 3except ImportError:    import Tkinter as tkdef event_handle(event):    # Replace the window's title with event.type: input key    root.title("{}: {}".format(str(event.type), event.keysym))if __name__ == '__main__':    root = tk.Tk()    event_sequence = '<KeyPress>'    root.bind(event_sequence, event_handle)    root.bind('<KeyRelease>', event_handle)    root.mainloop()