如何使用Tkinter传递多个命令?

问题描述

例如我有

root = Tk()
root.geometry("650x500+0+0")
def do_it():
    print("1st function")
def do_it1():
    print("2nd function")
button = Button(root,text="Change Config",width=20,height=3,bg="#26d142",fg="#030208",command=do_it)

但我希望它传递2个命令 就像

button = Button(root,command=do_it,do_it1)

解决方法

最简单的方法是创建同时运行两个功能并与Button一起使用的新功能

def do_it():
    print("1st function")
def do_it1():
    print("2nd function")

def new_function():
    do_it()
    do_it1()

button = Button(root,text="Change Config",command=new_function)

@ acw1668在评论中显示,您可以使用lambda

来写短一些
button = tk.Button(root,command=lambda:(do_it(),do_it1()))

但有时它的可读性较差。


编辑:

使用bind(...,add="+"),您还可以将许多功能分配给相同的小部件和事件。 bindunbind其中一个功能可能很有用,但我不知道您是否可以保持功能顺序。

它需要在函数中获取参数(event)。而且它需要定义自己的unbind(),因为原始的unbind()不能按预期工作,并且它删除了所有功能,而只删除了其中的一个功能。

我从Deleting and changing a tkinter event binding获得了unbid()

import tkinter as tk

# --- functions ---

def unbind(widget,sequence,funcid=None):
    """Unbind for this widget for event SEQUENCE the function identified with FUNCID."""

    # remove all functions
    if not funcid:
        widget.tk.call('bind',widget._w,'')
        return
    
    # get list with all functions
    func_callbacks = widget.tk.call('bind',None).split('\n')
    # remove one function from list
    new_callbacks = [l for l in func_callbacks if l[6:6 + len(funcid)] != funcid]
    # bind again other functions
    widget.tk.call('bind','\n'.join(new_callbacks))
    # clear
    widget.deletecommand(funcid)

def do_it(event=None):
    print("1st function")
    unbind(button,'<Button 1>',bind_id1)
    
def do_it1(event=None):
    print("2nd function")

def new_function():
    do_it()
    do_it1()

# --- main ---

root = tk.Tk()

button = tk.Button(root,text="Button 1",command=new_function)
button.pack()

button = tk.Button(root,text="Button 2",do_it1()))
button.pack()

button = tk.Button(root,text="Button 3")
button.pack()

bind_id1 = button.bind('<Button 1>',do_it,add="+")
bind_id2 = button.bind('<Button 1>',do_it1,add="+")
print(bind_id1)

root.mainloop()

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...