Why is Button parameter "command" executed when declared? [duplicate] Why is Button parameter "command" executed when declared? [duplicate] tkinter tkinter

Why is Button parameter "command" executed when declared? [duplicate]


It is called while the parameters for Button are being assigned:

command=Hello()

If you want to pass the function (not it's returned value) you should instead:

command=Hello

in general function_name is a function object, function_name() is whatever the function returns. See if this helps further:

>>> def func():...     return 'hello'... >>> type(func)<type 'function'>>>> type(func())<type 'str'>

If you want to pass arguments, you can use a lambda expression to construct a parameterless callable.

>>> hi=Button(frame, text="Hello", command=lambda: Goodnight("Moon"))

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:

import tkinter as tkdef hello():    print("Hi there!")main = tk.Tk()hi = tk.Button(main,text="Hello",command=lambda: hello()).pack()main.mainloop()