【问题标题】:Tkinter Function attached to Button executed immediately [duplicate]附加到按钮的Tkinter函数立即执行[重复]
【发布时间】:2016-10-20 12:03:15
【问题描述】:

我需要将一个函数附加到一个使用参数调用的按钮上。然而,当我编写如下代码时,代码在创建按钮时执行一次,然后不再执行。此外,如果我在将函数声明为按钮的属性时去掉参数和括号,代码也可以正常工作。如何仅在按下按钮时才调用带有参数的函数?

from Tkinter import *

root =Tk()

def function(parameter):
    print parameter

button = Button(root, text="Button", function=function('Test'))
button.pack()

root.mainloop()

【问题讨论】:

  • 感谢您的链接! @nbro

标签: python button tkinter


【解决方案1】:

解决方案是将函数作为 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 已经正确指出的那样,按钮属性是命令,而不是功能。

【讨论】:

  • 我被回答删除了,因为这显然是重复的。
猜你喜欢
  • 2015-03-02
  • 1970-01-01
  • 2018-12-19
  • 1970-01-01
  • 1970-01-01
  • 2016-01-28
  • 1970-01-01
  • 1970-01-01
  • 2018-08-11
相关资源
最近更新 更多