user14173492
user14173492

Reputation:

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()

Upvotes: 0

Views: 844

Answers (1)

tobias_k
tobias_k

Reputation: 82949

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; 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
  • by binding the key to the Button, it will only be registered when the button has focus (e.g. when pressing Tab until the button is "highlighted")
  • 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

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, e.g. Return, and bind that to root or use bind_all so it is bound to all widgets.

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
  • by focusing it and pressing space, emulating a click
  • by pressing the Return key, calling the key event binding

Upvotes: 2

Related Questions