为什么Button参数“命令”执行时声明? [英] Why is Button parameter "command" executed when declared?
问题描述
我是Python的新手,试图用tkinter编写程序。
为什么下面的Hello函数执行?据我所知,回调只会在按下按钮时执行?我很困惑...
>>> def Hello():
print(Hi there!)
>>> hi = Button(frame,text =Hello,command = Hello())
嗨!
>>>>
c> 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))
简单地说,因为晚安(Moon)
是在lambda中,它不会立即执行,而是等待直到按钮被点击。
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!
>>>
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.
这篇关于为什么Button参数“命令”执行时声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!