HOWTO · Tkinter
Cómo vincular varios comandos al botón Tkinter
Este tutorial introduce cómo enlazar varios comandos al botón de Tkinter. Ejecutará múltiples comandos cuando el botón sea presionado.
En este tutorial, demostraremos cómo enlazar varios comandos a un botón de Tkinter. Se ejecutarán varios comandos después de hacer clic en el botón.
Vincular varios comandos al botón de Tkinter
El botón de Tkinter sólo tiene una propiedad de command, de modo que múltiples comandos o funciones deben ser envueltos en una función que esté ligada a este command.
Podríamos usar lambda para combinar múltiples comandos como,
def command():
return [funcA(), funcB(), funcC()]
Esta función lambda ejecutará funcA, funcB, y funcC una por una.
Ejemplo de labmda bind multiple commands
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()
Combinar funciones en una sola función
def combineFunc(self, *funcs):
def combinedFunc(*args, **kwargs):
for f in funcs:
f(*args, **kwargs)
return combinedFunc
La función anterior define una función dentro de una función y luego devuelve el objeto de la función.
for f in funcs:
f(*args, **kwargs)
Ejecuta todas las funciones dadas en el paréntesis 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()