Why is Button parameter “command” executed when declared?

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!
>>>

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

You can also use a lambda expression as the command argument:

import tkinter as tk
def hello():
    print("Hi there!")

main = tk.Tk()
hi = tk.Button(main,text="Hello",command=lambda: hello()).pack()
main.mainloop()


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x