python中的WASD输入

JGe*_*kis 4 python keyboard tkinter

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

Bry*_*ley 5

使用 tkinter 等 GUI 工具包执行此操作的方法是创建绑定。绑定表示“当此小部件具有焦点并且用户按下 X 键时,调用此函数”。

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

在一个简单的情况下,您只想检测四个键,调用单个函数的四个绑定(每个键一个)可能是最有意义的。例如,在 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()
Run Code Online (Sandbox Code Playgroud)