如何将多个命令绑定到 Tkinter 按钮

在本教程中,我们将演示如何将多个命令绑定到 Tkinter 按钮。单击该按钮后将执行多个命令。

将多个命令绑定到 Tkinter Button

Tkinter 按钮只有一个 command 属性,因此应将多个命令或函数组合在一起,然后此单函数绑定到按钮的 command

我们可以用 lambda 组合多个命令,

command=lambda:[funcA(), funcB(), funcC()]

lambda 函数将分别执行 funcAfuncBfuncC

labmda 绑定多个函数举例

try:
    import Tkinter as tk
except:
    import tkinter as tk
    

class Test():
   def __init__(self):
       self.root = tk.Tk()
       self.root.geometry('200x100')
       self.button = tk.Button(self.root,
                          text = 'Click Me',
                          command=lambda:[self.funcA(), self.funcB(), self.funcC()])
       self.button.pack()

       self.labelA = tk.Label(self.root, text="A")
       self.labelB = tk.Label(self.root, text="B")
       self.labelC = tk.Label(self.root, text="C")

       self.labelA.pack()
       self.labelB.pack()
       self.labelC.pack()
       
       self.root.mainloop()

   def funcA(self):
       self.labelA["text"] = "A responds"

   def funcB(self):
       self.labelB["text"] = "B responds"
   def funcC(self):
       self.labelC["text"] = "C responds"
       
app = Test()

Tkinter 多个函数绑定到按钮命令

将函数组合为一个函数

   def combineFunc(self, *funcs):
       def combinedFunc(*args, **kwargs):
            for f in funcs:
                f(*args, **kwargs)
       return combinedFunc

上面的函数在函数内部定义一个函数,然后返回该函数对象。

for f in funcs:
                f(*args, **kwargs)

It executes all the functions given in the parenthesis of combineFunc.

try:
    import Tkinter as tk
except:
    import tkinter as tk
    

class Test():
   def __init__(self):
       self.root = tk.Tk()
       self.root.geometry('200x100')
       self.button = tk.Button(self.root,
                          text = 'Click Me',
                          command = self.combineFunc(self.funcA, self.funcB, self.funcC))
       self.button.pack()

       self.labelA = tk.Label(self.root, text="A")
       self.labelB = tk.Label(self.root, text="B")
       self.labelC = tk.Label(self.root, text="C")

       self.labelA.pack()
       self.labelB.pack()
       self.labelC.pack()
       
       self.root.mainloop()

   def combineFunc(self, *funcs):
       def combinedFunc(*args, **kwargs):
            for f in funcs:
                f(*args, **kwargs)
       return combinedFunc

   def funcA(self):
       self.labelA["text"] = "A responds"

   def funcB(self):
       self.labelB["text"] = "B responds"

   def funcC(self):
       self.labelC["text"] = "C responds"
       
app = Test()

Related Articles - Tkinter Button

  • 如何向 Tkinter 按钮命令中传递参数
  • 如何使用按钮关闭 Tkinter 窗口
  • 如何更改 Tkinter 按钮状态
  • 如何单击 Tkinter 中的按钮来创建新窗口
  • comments powered by Disqus