Python-为什么在声明时执行Button参数“ command”?
我是Python的新手,正在尝试使用tkinter编写程序。为什么执行下面的Hello函数?据我了解,仅在按下按钮时才会执行回调?我很困扰…
>>> def Hello():        print("Hi there!")
>>> hi=Button(frame,text="Hello",command=Hello())
Hi there!
>>> 
回答:
在为其Button分配参数时调用它:
command=Hello()如果要传递函数(不是返回值),则应改为:
command=Hello通常function_name是一个函数对象,function_name()就是函数返回的结果。看看这是否有帮助:
>>> def func():...     return 'hello'
... 
>>> type(func)
<type 'function'>
>>> type(func())
<type 'str'>
如果要传递参数,则可以使用lambda表达式构造无参数可调用对象。
>>> hi=Button(frame, text="Hello", command=lambda: Goodnight("Moon"))简而言之,因为Goodnight("Moon")它位于lambda中,所以它不会立即执行,而是要等到单击按钮后才能执行。
以上是 Python-为什么在声明时执行Button参数“ command”? 的全部内容, 来源链接: utcz.com/qa/415522.html

