为什么在声明时执行Button参数"command"?

wja*_*obw 15 python tkinter callback

我是Python新手并试图用tkinter编写程序.为什么下面的Hello函数被执行了?据我了解,回调只会在按下按钮时执行?我很迷茫...

>>> def Hello():
        print("Hi there!")

>>> hi=Button(frame,text="Hello",command=Hello())
Hi there!
>>> 
Run Code Online (Sandbox Code Playgroud)

mac*_*mac 31

Button在分配参数时调用它:

command=Hello()
Run Code Online (Sandbox Code Playgroud)

如果你想传递函数(不是它的返回值),你应该改为:

command=Hello
Run Code Online (Sandbox Code Playgroud)

通常function_name是一个函数对象,function_name()无论函数返回什么.看看这是否有助于进一步:

>>> def func():
...     return 'hello'
... 
>>> type(func)
<type 'function'>
>>> type(func())
<type 'str'>
Run Code Online (Sandbox Code Playgroud)

如果要传递参数,可以使用lambda表达式构造无参数的可调用对象.

>>> hi=Button(frame, text="Hello", command=lambda: Goodnight("Moon"))
Run Code Online (Sandbox Code Playgroud)

简单地说,因为Goodnight("Moon")在lambda中,它不会立即执行,而是等到单击按钮.