Tkinter功能附加到Button立即执行 [英] Tkinter Function attached to Button executed immediately
问题描述
我需要的是将函数附加到使用参数调用的按钮上.但是,当我按如下方式编写代码时,创建按钮后代码将执行一次,然后不再执行.另外,如果我声明该函数为按钮的属性,那么我摆脱了参数和括号,代码就可以正常工作.仅当按下按钮时,如何才能通过参数调用函数?
What I need is to attach a function to a button that is called with a parameter. When I write the code as below however, the code is executed once when the button is created and then no more. Also, the code works fine if I get rid of the parameter and parentheses when I declare the function as an attribute of the button. How can I call the function with a parameter only when the button is pressed?
from Tkinter import *
root =Tk()
def function(parameter):
print parameter
button = Button(root, text="Button", function=function('Test'))
button.pack()
root.mainloop()
推荐答案
解决方案是将函数作为lambda传递:
The solution is to pass the function as a lambda:
from Tkinter import *
root =Tk()
def callback(parameter):
print parameter
button = Button(root, text="Button", command=lambda: callback(1))
button.pack()
root.mainloop()
此外,正如@nbro已经正确指出的那样,button属性是命令,而不是功能.
Also, as @nbro already correctly pointed out, the button attribute is command, not function.
这篇关于Tkinter功能附加到Button立即执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!