This question already has an answer here:
I'm new to Python and trying to write a program with tkinter. Why is the Hello-function below executed? As I understand it, the callback would only be executed when the button is pressed? I am very confused...
>>> def Hello():
print("Hi there!")
>>> hi=Button(frame,text="Hello",command=Hello())
Hi there!
>>>
It is called while the parameters for
Button
are being assigned:If you want to pass the function (not it's returned value) you should instead:
in general
function_name
is a function object,function_name()
is whatever the function returns. See if this helps further:If you want to pass arguments, you can use a lambda expression to construct a parameterless callable.
Simply put, because
Goodnight("Moon")
is in a lambda, it won't execute right away, instead waiting until the button is clicked.You can also use a lambda expression as the command argument: