简体   繁体   English

tkinter 调用两个函数

[英]tkinter call two functions

Is it possible to make it so that a Tkinter button calls two function?是否可以使 Tkinter 按钮调用两个 function?

some thing like this maybe?:可能是这样的事情?:

from Tkinter import *

admin = Tk()
def o():
    print '1'

def t():
    print '2'
button = Button(admin, text='Press', command=o, command=t)
button.pack()

Make a new function that calls both:制作一个新的 function 调用两者:

def o_and_t():
    o()
    t()
button = Button(admin, text='Press', command=o_and_t)

Alternatively, you can use this fun little function:或者,您可以使用这个有趣的小 function:

def sequence(*functions):
    def func(*args, **kwargs):
        return_value = None
        for function in functions:
            return_value = function(*args, **kwargs)
        return return_value
    return func

Then you can use it like this:然后你可以像这样使用它:

button = Button(admin, text='Press', command=sequence(o, t))

The syntax you're trying for doesn't exist unfortunately.不幸的是,您尝试的语法不存在。 What you'd need to do is make a wrapper function that runs both of your functions.您需要做的是制作一个运行您的两个功能的包装器 function。 A lazy solution would be something like:一个懒惰的解决方案是这样的:

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

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

you can use the sample way with lambda like this:您可以像这样使用 lambda 的示例方式:

button = Button(text="press", command=lambda:[function1(), function2()])

Correct me if I'm wrong, but whenever I needed a button to operate multiple functions, I would establish the button once:如果我错了,请纠正我,但是每当我需要一个按钮来操作多个功能时,我都会建立一次按钮:

button = Button(admin, text='Press', command=o)

And then add another function using the .configure() :然后使用.configure()添加另一个 function :

button.configure(command=t)

Added to your script, it would look like this添加到您的脚本中,它看起来像这样

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

This could run multiple functions, well as a function and a admin.destroy or any other command without using a global variable or having to redefine anything这可以运行多个函数,以及 function 和admin.destroy或任何其他命令,而无需使用全局变量或重新定义任何内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM