简体   繁体   English

如何在Tkinter中进行多个键

[英]How to make multiple keys in Tkinter

I'm trying to make multiple keys to press but the command focus_set() makes only one button available to press, the rest of the keys doesnt work. 我正在尝试按下多个键,但是命令focus_set()仅使一个按钮可用,其余键不起作用。 The button works if you click it but I want to use the button through the keyboard so how do I make so every key works 如果您单击该按钮,则该按钮有效,但是我想通过键盘使用该按钮,因此,我该怎么做,所以每个键都有效

btnUp = tkinter.Button(master=None, text="Up", command=up)
btnUp.bind("w", up)
btnUp.focus_set()
btnUp.pack(side=tkinter.TOP, anchor=tkinter.W)

btnRight = tkinter.Button(master=None, text="Right", command=right)
btnRight.bind("d", right)
btnRight.focus_set()
btnRight.pack(side=tkinter.TOP, anchor=tkinter.W)

btnLeft = tkinter.Button(master=None, text="Left", command=left)
btnLeft.bind("a", left)
btnLeft.focus_set()
btnLeft.pack(side=tkinter.TOP, anchor=tkinter.W)

btnDown = tkinter.Button(master=None, text="Down", command=down)
btnDown.bind("s", down)
btnDown.focus_set()
btnDown.pack(side=tkinter.BOTTOM, anchor=tkinter.W)

You have to bind to the widget that the Buttons are in. For the most effectiveness, bind to root. 您必须绑定到Buttons所在的小部件。为了获得最大的效果,请绑定到root。

btnUp = tkinter.Button(master=None, text="Up", command=up)
root.bind("w", up)
btnUp.pack(side=tkinter.TOP, anchor=tkinter.W)

If you don't have access to root in that scope you can add this to the top: 如果您在该范围内无权访问root,则可以将其添加到顶部:

root = tkinter._default_root

Remember that the Button command callback and the bind callback have different signatures, so you need to define the functions with an optional event argument like this: 请记住,Button命令回调和bind回调具有不同的签名,因此您需要使用可选的事件参数来定义函数,如下所示:

def up(event=None):
    # code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM