为什么按钮参数“命令”在声明时被执行?[重复]
- 2025-02-08 08:52:00
- admin 原创
- 44
问题描述:
我是 Python 新手,正在尝试使用 tkinter 编写程序。为什么会执行下面的 Hello 函数?据我了解,只有按下按钮时才会执行回调?我很困惑...
>>> def Hello():
print("Hi there!")
>>> hi=Button(frame,text="Hello",command=Hello())
Hi there!
>>>
解决方案 1:
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 中,所以它不会立即执行,而是等到按钮被点击。
解决方案 2:
您还可以使用 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()
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD