HOWTO · Tkinter
Como atualizar o texto do Botão Tkinter
Este tutorial demonstra como atualizar o texto do Botão Tkinter.
Neste tutorial, vamos introduzir como alterar o texto do botão Tkinter. É semelhante aos métodos para mudar o texto da etiqueta Tkinter,
- Método
StringVar - Botão
textMétodo de propriedade
Utilize StringVar para mudar o texto do botão Tkinter
StringVar é um tipo de construtor de Tkinter para criar a variável string Tkinter.
Depois de associarmos a variável StringVar ao widget Tkinter Button, Tkinter atualizará o texto deste Button quando a variável for modificada.
import tkinter as tk
class Test:
def __init__(self):
self.root = tk.Tk()
self.root.geometry("250x100")
self.text = tk.StringVar()
self.text.set("Original Text")
self.buttonA = tk.Button(self.root, textvariable=self.text)
self.buttonB = tk.Button(
self.root, text="Click to change text", command=self.changeText
)
self.buttonA.pack(side=tk.LEFT)
self.buttonB.pack(side=tk.RIGHT)
self.root.mainloop()
def changeText(self):
self.text.set("Updated Text")
app = Test()
self.text = tk.StringVar()
self.text.set("Original Text")
O construtor Tkinter não poderia iniciar a variável string com a string como self.text = tk.StringVar("Text").
Devemos chamar o método set para definir o valor StringVar, como self.text.set("Original Text").
self.buttonA = tk.Button(self.root, textvariable=self.text)
A variável StringVar self.text é atribuída à opção textvariable de self.buttonA. Tkinter atualizará o texto de self.buttonA automaticamente se o self.text for modificado.
Propriedade text do botão Tkinter para alterar o texto do botão
Outra solução para alterar o texto do botão Tkinter é alterar a propriedade text do botão.
import tkinter as tk
class Test:
def __init__(self):
self.root = tk.Tk()
self.root.geometry("250x100")
self.buttonA = tk.Button(self.root, text="Original Text")
self.buttonB = tk.Button(
self.root, text="Click to change text", command=self.changeText
)
self.buttonA.pack(side=tk.LEFT)
self.buttonB.pack(side=tk.RIGHT)
self.root.mainloop()
def changeText(self):
self.buttonA["text"] = "Updated Text"
app = Test()
O text é uma chave do objeto Button cujo texto poderia ser iniciado com text="Original Text" e também poderia ser atualizado atribuindo o novo valor ao text.
O método tk.Button.configure() também poderia alterar a propriedade text para alterar o texto de Tkinter Button, como mostrado abaixo.
import tkinter as tk
class Test:
def __init__(self):
self.root = tk.Tk()
self.root.geometry("250x100")
self.buttonA = tk.Button(self.root, text="Original Text")
self.buttonB = tk.Button(
self.root, text="Click to change text", command=self.changeText
)
self.buttonA.pack(side=tk.LEFT)
self.buttonB.pack(side=tk.RIGHT)
self.root.mainloop()
def changeText(self):
self.buttonA.configure(text="Updated Text")
app = Test()