WASD input in python WASD input in python tkinter tkinter

WASD input in python


The way you do this with a GUI toolkit like tkinter is to create a binding. Bindings say "when this widget has focus and the user presses key X, call this function".

There are many ways to accomplish this. You can, for example, create a distinct binding for each character. Or, you could create a single binding that fires for any character. With these bindings, you can have them each call a unique function, or you can have all the bindings call a single function. And finally, you can put the binding on a single widget, or you can put the binding on all widgets. It all depends on exactly what you are trying to accomplish.

In a simple case where you only want to detect four keys, four bindings (one for each key) calling a single function makes perhaps the most sense. For example, in python 2.x it would look something like this:

import Tkinter as tkclass Example(tk.Frame):    def __init__(self, parent):        tk.Frame.__init__(self, parent, width=400,  height=400)        self.label = tk.Label(self, text="last key pressed:  ", width=20)        self.label.pack(fill="both", padx=100, pady=100)        self.label.bind("<w>", self.on_wasd)        self.label.bind("<a>", self.on_wasd)        self.label.bind("<s>", self.on_wasd)        self.label.bind("<d>", self.on_wasd)        # give keyboard focus to the label by default, and whenever        # the user clicks on it        self.label.focus_set()        self.label.bind("<1>", lambda event: self.label.focus_set())    def on_wasd(self, event):        self.label.configure(text="last key pressed: " + event.keysym);if __name__ == "__main__":    root = tk.Tk()    Example(root).pack(fill="both", expand=True)    root.mainloop()