绑定到tkinter中每个键的键绑定 [英] Keybind that binds to every key in tkinter

查看:67
本文介绍了绑定到tkinter中每个键的键绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python创建一个交互式游戏,并且我试图以按任意键继续"的说明进行介绍.我在将所有键绑定到单个操作时遇到了一些困难.

I am creating an interactive game with Python, and I am trying to make an introduction with the instruction "Press any key to continue." I am having some difficulty with binding all the keys to a single action.

我尝试绑定到'< Any>',但显示错误消息.

I have tried binding to '<Any>', but it displays an error message.

from tkinter import *

window = Tk()

root = Canvas(window, width=500, height=500)

def testing():
    print("Hello World!")

root.bind_all('<Any>', testing)

root.pack()
root.mainloop()

如前所述,'< Any>'键盘绑定导致读取错误消息: tkinter.TclError:错误事件类型或键盘符号"Any" .有没有将每个键绑定到操作的简单方法?

As mentioned before, the '<Any>' keybind results in an error message reading: tkinter.TclError: bad event type or keysym "Any". Is there a simple way to bind every key to an action?

推荐答案

我使用< Key> ,它将捕获任何键盘事件并显示"Hello".并且不要忘记在 testing()中指定 event event = None 参数.

I use <Key> it will capture any keyboard event and print "Hello". And don't forget to specify event or event=None parameter in 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()

这篇关于绑定到tkinter中每个键的键绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆