tkinter调用两个函数

2024-04-29 17:10:58 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以使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()

Tags: 函数textfromimportadmintkinterdefbutton
3条回答

很遗憾,您尝试的语法不存在。您需要做的是创建一个包装器函数来运行这两个函数。一个懒惰的解决方案是:

def multifunction(*args):
    for function in args:
        function(s)

cb = lambda: multifunction(o, t)
button = Button(admin, text='Press', command=cb)

创建一个新函数,该函数同时调用:

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))

如果我错了,请纠正我,但每当我需要一个按钮来操作多个功能时,我会建立一次该按钮:

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或任何其他命令,而无需使用全局变量或重新定义任何内容

相关问题 更多 >