Tkinter is a standard Python interface to the Tk GUI toolkit shipped with Python. Modifying the text displayed on a label is a fundamental operation in Tkinter. Let me demonstrate various methods for changing label text dynamically.
Creating a Basic Label
Let’s start by creating a simple Tkinter window with a label:
import tkinter as tk
root = tk.Tk()
root.title("Label Text Change Example")
my_label = tk.Label(root, text="Initial Label Text")
my_label.pack(pady=20)
root.mainloop()
This code will display a window with the label “Initial Label Text”.
Changing Label Text Using config()
The most direct way to change a label’s text is by using the config()
method. This method allows you to change any of the label’s properties, including its text.
Example with a Button
Here’s an example that changes the label’s text when a button is clicked:
import tkinter as tk
def change_text():
my_label.config(text="New Label Text")
root = tk.Tk()
root.title("Label Text Change Example")
my_label = tk.Label(root, text="Initial Label Text")
my_label.pack(pady=20)
change_button = tk.Button(root, text="Change Text", command=change_text)
change_button.pack(pady=10)
root.mainloop()
Clicking the “Change Text” button will execute the change_text()
function, which updates the label’s text using my_label.config(text="New Label Text")
.
Using StringVar() for Dynamic Updates
For more dynamic updates, especially when you need to update the label text based on variables, you can use StringVar()
.
import tkinter as tk
def update_text():
text_variable.set("Dynamic Label Text")
root = tk.Tk()
root.title("Label Text Change Example")
text_variable = tk.StringVar()
text_variable.set("Initial Label Text")
my_label = tk.Label(root, textvariable=text_variable)
my_label.pack(pady=20)
update_button = tk.Button(root, text="Update Text", command=update_text)
update_button.pack(pady=10)
root.mainloop()
Here, the label’s textvariable
is linked to text_variable
. Any changes to text_variable
will automatically update the label’s text.
Changing Text Based on User Input
You can also change the label’s text based on user input from an Entry
widget.
import tkinter as tk
def update_from_entry():
input_text = entry_widget.get()
my_label.config(text=input_text)
root = tk.Tk()
root.title("Label Text Change Example")
my_label = tk.Label(root, text="Initial Label Text")
my_label.pack(pady=20)
entry_widget = tk.Entry(root)
entry_widget.pack(pady=10)
update_button = tk.Button(root, text="Update from Entry", command=update_from_entry)
update_button.pack(pady=10)
root.mainloop()
The update_from_entry()
function retrieves the text from the entry_widget
and updates the label’s text with it.