python 中的 WASD 输入

WASD input in python

在python中,如何接收键盘输入。我很清楚 input("...") 的控制台输入,但我更关心在控制台 window 未激活时接收键盘输入。例如,如果我创建了一个 Tkinter 屏幕实例,我该如何检查是否按下了 "w"。然后,如果该语句返回 true,我可以相应地移动一个对象。

使用 tkinter 等 GUI 工具包执行此操作的方法是创建绑定。绑定说 "when this widget has focus and the user presses key X, call this function".

有很多方法可以做到这一点。例如,您可以为每个字符创建不同的绑定。或者,您可以创建一个针对任何角色触发的单一绑定。使用这些绑定,您可以让它们各自调用一个唯一的函数,或者您可以让所有绑定调用一个函数。最后,您可以将绑定放在单个小部件上,也可以将绑定放在所有小部件上。这完全取决于您要完成的目标。

在您只想检测四个键的简单情况下,调用单个函数的四个绑定(每个键一个)可能最有意义。例如,在 python 2.x 中,它看起来像这样:

import Tkinter as tk

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