【发布时间】:2012-01-06 07:59:57
【问题描述】:
我是 Python 新手,正在尝试使用 tkinter 编写程序。 为什么会执行下面的 Hello-function?据我了解,回调只会在按下按钮时执行?我很困惑……
>>> def Hello():
print("Hi there!")
>>> hi=Button(frame,text="Hello",command=Hello())
Hi there!
>>>
【问题讨论】:
我是 Python 新手,正在尝试使用 tkinter 编写程序。 为什么会执行下面的 Hello-function?据我了解,回调只会在按下按钮时执行?我很困惑……
>>> 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 expression 构造无参数可调用对象。
>>> hi=Button(frame, text="Hello", command=lambda: Goodnight("Moon"))
简单地说,因为Goodnight("Moon")在一个lambda中,它不会立即执行,而是等到按钮被点击。
【讨论】:
def func(par1, par2): 在后者中,您只需使用不带括号的函数名称,正如我在回答中概述的那样。既然你是 python 的新手,我可以建议this reading 吗?它很容易上手,而且非常有趣。
您也可以使用 lambda 表达式作为命令参数:
import tkinter as tk
def hello():
print("Hi there!")
main = tk.Tk()
hi = tk.Button(main,text="Hello",command=lambda: hello()).pack()
main.mainloop()
【讨论】: