我正在用Python创建一个交互式游戏,我试图用“按任意键继续”进行介绍。我遇到了一些麻烦,因为很难将所有键绑定到单个动作。
我已尝试绑定到'<Any>'
,但它显示错误消息。
from tkinter import *
window = Tk()
root = Canvas(window, width=500, height=500)
def testing():
print("Hello!")
def countdown(count, label):
label['text'] = count
if count > -1:
root.after(1000, countdown, count-1, label)
elif count == 0:
label['text'] = 'Time Expired'
elif count < 0:
label.destroy()
root.bind_all('<Any>', testing)
root.pack()
root.mainloop()
如前所述,'<Any>'
keybind会导致错误消息:tkinter.TclError: bad event type or keysym "Any"
。有没有一种简单的方法将每个键绑定到一个动作?
我使用<Key>
它将捕获任何键盘事件并打印“Hello”。并且不要忘记在event
中指定event=None
或testing()
参数。
from tkinter import *
window = Tk()
root = Canvas(window, width=500, height=500)
def testing(event):
print("Hello!")
def countdown(count, label):
label['text'] = count
if count > -1:
root.after(1000, countdown, count-1, label)
elif count == 0:
label['text'] = 'Time Expired'
elif count < 0:
label.destroy()
root.bind_all('<Key>', testing)
root.pack()
root.mainloop()