最简单的方法是创建一个新的函数来运行这两个函数并将其与 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,text="Change Config", command=lambda:(do_it(), do_it1()))
但有时它的可读性可能会降低。
编辑:
使用bind(..., add="+"),您还可以为同一个小部件和事件分配许多功能。对bind 和unbind 功能之一可能有用,但我不知道您是否可以保持功能顺序。
它需要在函数中获取参数(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, sequence, '')
return
# get list with all functions
func_callbacks = widget.tk.call('bind', widget._w, sequence, 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', widget._w, sequence, '\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", command=lambda:(do_it(), 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()