Tkinter, Python’s standard GUI toolkit, allows you to create interactive applications. Updating the text of a label is a common task. Let’s explain how to change the text of a Tkinter label dynamically.
Basic Label Creation
First, let’s create a basic Tkinter window with a label.
import tkinter as tk
root = tk.Tk()
root.title("Label Update Example")
label = tk.Label(root, text="Initial Text")
label.pack(pady=20)
root.mainloop()
This code creates a window with a label that initially displays “Initial Text”.
Updating Label Text
To update the label’s text, you can use the config()
method of the label widget.
Example with a Button
Here’s an example that updates the label text when a button is clicked:
import tkinter as tk
def update_label():
label.config(text="Updated Text")
root = tk.Tk()
root.title("Label Update Example")
label = tk.Label(root, text="Initial Text")
label.pack(pady=20)
button = tk.Button(root, text="Update Label", command=update_label)
button.pack(pady=10)
root.mainloop()
When the “Update Label” button is clicked, the update_label()
function is called. This function uses label.config(text="Updated Text")
to change the label’s text.
Updating with a Variable
You can also use a StringVar
to dynamically update the label’s text based on a variable.
import tkinter as tk
def update_label():
text_var.set("Text updated from variable")
root = tk.Tk()
root.title("Label Update Example")
text_var = tk.StringVar()
text_var.set("Initial Text")
label = tk.Label(root, textvariable=text_var)
label.pack(pady=20)
button = tk.Button(root, text="Update Label", command=update_label)
button.pack(pady=10)
root.mainloop()
In this example, textvariable=text_var
associates the label’s text with the StringVar
. When the button is clicked, text_var.set("Text updated from variable")
updates the variable, which in turn updates the label’s text.
Updating Label Text from Input
Here’s an example that takes input from an entry widget and updates the label’s text with the input:
import tkinter as tk
def update_label():
new_text = entry.get()
label.config(text=new_text)
root = tk.Tk()
root.title("Label Update Example")
label = tk.Label(root, text="Initial Text")
label.pack(pady=20)
entry = tk.Entry(root)
entry.pack(pady=10)
button = tk.Button(root, text="Update Label", command=update_label)
button.pack(pady=10)
root.mainloop()
This code takes the text from the entry widget using entry.get()
and updates the label’s text with it.