Como unir vários comandos ao botão Tkinter
Neste tutorial, vamos demonstrar como ligar comandos múltiplos a um Botão Tkinter. Os comandos múltiplos serão executados após o botão ser clicado.
Ligar comandos múltiplos ao Botão Tkinter
O botão Tkinter tem apenas uma propriedade command
, de modo que vários comandos ou funções devem ser envolvidos em uma função que está vinculada a este command
.
Poderíamos utilizar o lambda
para combinar vários comandos como,
command=lambda:[funcA(), funcB(), funcC()]
Esta função lambda
executará funcA
, funcB
, e funcC
um por um.
Exemplo de labmda
para ligar comandos múltiplos
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 funções para uma única função
def combineFunc(self, *funcs):
def combinedFunc(*args, **kwargs):
for f in funcs:
f(*args, **kwargs)
return combinedFunc
A função acima define uma função dentro de uma função e depois retorna o objeto função.
for f in funcs:
f(*args, **kwargs)
Ele executa todas as funções dadas no parêntese do 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()