是否可以使Tkinter按钮调用两个函数?
有些事情可能会这样吗?:
from Tkinter import *
admin = Tk()
def o():
print '1'
def t():
print '2'
button = Button(admin, text='Press', command=o, command=t)
button.pack()
答案 0 :(得分:8)
创建一个调用两者的新函数:
def o_and_t():
o()
t()
button = Button(admin, text='Press', command=o_and_t)
或者,您可以使用这个有趣的小功能:
def sequence(*functions):
def func(*args, **kwargs):
return_value = None
for function in functions:
return_value = function(*args, **kwargs)
return return_value
return func
然后你可以像这样使用它:
button = Button(admin, text='Press', command=sequence(o, t))
答案 1 :(得分:1)
不幸的是,您尝试的语法不存在。您需要做的是创建一个运行两个函数的包装函数。懒惰的解决方案就像:
def multifunction(*args):
for function in args:
function(s)
cb = lambda: multifunction(o, t)
button = Button(admin, text='Press', command=cb)
答案 2 :(得分:1)
您可以像这样在 lambda 中使用示例方式:
button = Button(text="press", command=lambda:[function1(), function2()])
答案 3 :(得分:0)
如果我错了,请纠正我,但每当我需要一个按钮来操作多个功能时,我会建立一次按钮:
button = Button(admin, text='Press', command=o)
然后使用.configure()
添加另一个函数:
button.configure(command=t)
添加到您的脚本中,它看起来像这样
from Tkinter import *
admin = Tk()
def o():
print '1'
def t():
print '2'
button = Button(admin, text='Press', command=o)
button.configure(command=t)
button.pack()
这可以运行多个函数,以及函数和admin.destroy
或任何其他命令,而不使用全局变量或必须重新定义任何内容