如何解决如何使用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="+")
,您还可以将许多功能分配给相同的小部件和事件。 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,'')
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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。