简体   繁体   English

Tkinter 键绑定在 Python 中不起作用

[英]Tkinter Key binding doesn't work in Python

I am trying to make a button that increases money or something, but i am just trying to test it out in another project我正在尝试制作一个增加金钱或其他东西的按钮,但我只是想在另一个项目中对其进行测试

This is my code for the button这是我的按钮代码

global counterCheck
counterCheck = 0



def checkClick():
    global counterCheck
    counterCheck += 1
    textClick.config(text=counterCheck)


bttt = Button(root, width=1720, height=600, text="Click Here", command=checkClick)

bttt.bind("<space>", checkClick())
bttt.pack()

There are actually multiple problems with your code.您的代码实际上存在多个问题。 The first one is a common problem , but there is more:第一个是一个常见问题,但还有更多:

  • you execute the function and then bind the result of that function, which is None , to the event;您执行该函数,然后将该函数的结果(即None绑定到事件; instead, you have to bind the function itself相反,您必须绑定函数本身
  • also, unlike with Button.command , when a function is called via bind , it will get an parameter, the event that triggered it此外,与Button.command不同,当通过bind调用函数时,它将获得一个参数,即触发它的事件
  • by binding the key to the Button, it will only be registered when the button has focus (eg when pressing Tab until the button is "highlighted")通过将键绑定到按钮,它只会在按钮有焦点时注册(例如,当按下 Tab 直到按钮被“突出显示”时)
  • and the button already has a binding to be "clicked" when it is focused and Space is pressed, so adding another binding would make it react twice并且按钮在聚焦并按下 Space 时已经一个要“单击”的绑定,因此添加另一个绑定会使其反应两次

I actually did not manage to unbind the "press on space-key" action from the Button, so one workaround (besides never giving the button the focus) would be to use a different key, eg Return , and bind that to root or use bind_all so it is bound to all widgets.我实际上并没有设法从 Button unbind “按下空格键”操作的unbind ,所以一种解决方法(除了从不给按钮焦点)是使用不同的键,例如Return ,并将其绑定到root或使用bind_all所以它绑定到所有小部件。

def checkClick(*unused): # allow optional unused parameters
    ...

root.bind("<Return>", checkClick) # function itself, no (), root, and Return

After this, there are three ways to trigger the button:在此之后,触发按钮的方式有以下三种:

  • by clicking it, calling the command通过单击它,调用command
  • by focusing it and pressing space, emulating a click通过聚焦并按下空格,模拟点击
  • by pressing the Return key, calling the key event binding通过按Return键,调用按键事件绑定

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

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