如何將多個命令繫結到 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