0

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()
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • With `bttt.bind("", checkClick())` you bind the _result_ of the function call to the event, not the function itself. – tobias_k Sep 05 '20 at 13:43
  • However, that's actually not the only problem. For `bind`, the function also has to accept an argument, and by binding the event to the button, the button needs to have focus, and in that case it will be triggered on space anyway. – tobias_k Sep 05 '20 at 13:48
  • Ive added an answer, do mark it as the answer, if it helped, to close the Q – Delrius Euphoria Sep 21 '20 at 14:15

1 Answers1

2

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
tobias_k
  • 81,265
  • 12
  • 120
  • 179