Comment lier plusieurs commandes au bouton Tkinter
Dans ce tutoriel, nous allons démontrer comment lier plusieurs commandes à un bouton Tkinter. Les commandes multiples seront exécutées après que le bouton ait été cliqué.
Lier plusieurs commandes au bouton Tkinter
Le bouton Tkinter n’a qu’une seule propriété command, de sorte que plusieurs commandes ou fonctions doivent être enveloppées dans une fonction liée à cette command.
Nous pourrions utiliser lambda pour combiner plusieurs commandes comme,
def command():
return [funcA(), funcB(), funcC()]
Cette fonction lambda exécutera funcA, funcB, et funcC un par un.
Exemple de commandes multiples de labmda bind
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()

Combinaison de fonctions en une seule fonction
def combineFunc(self, *funcs):
def combinedFunc(*args, **kwargs):
for f in funcs:
f(*args, **kwargs)
return combinedFunc
La fonction ci-dessus définit une fonction à l’intérieur d’une fonction et retourne ensuite l’objet fonction.
for f in funcs:
f(*args, **kwargs)
Elle exécute toutes les fonctions données dans la parenthèse de 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()
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook