Tkinter function calling on its own Tkinter function calling on its own tkinter tkinter

Tkinter function calling on its own


Consider this line of code:

canvas.bind("w", ball_disappear())

It has exactly the same effect as this:

result = ball_disappear()canvas.bind("w", result)

When you bind an event, you must give it a callable. Typically that takes the form of a reference to a function, though it can also be the result of a call to lambda or functools.partial, or even your own function if that function returns another function.

Thus, the proper way to bind ball_disappear is like this:

canvas.bind("w", ball_disappear)

Your code still won't work, however, because of two other errors in your code.

First, the canvas doesn't get keyboard events by default. You must explicitly give it the keyboard focus, so sometime after creating the canvas you need to do this:

canvas.focus_set()

Second, when you bind a function to an event, the function that is called will be passed an object that has information about the event. Thus, you need to define your function like the following even if you don't plan to use the parameter in your code:

def ball_disappear(event):