Python tkinter trick
This trick allows you to link a label's text directly to a variable, so the label updates automatically whenever the variable changes.
Example: Dynamic Label with StringVar
import tkinter as tk
# Create the main window
root = tk.Tk()
root.title("Dynamic Label with StringVar")
# Create a StringVar to hold the label's text
dynamic_text = tk.StringVar()
dynamic_text.set("Hello, Tkinter!")
# Create a label that uses StringVar
label = tk.Label(root, textvariable=dynamic_text, font=("Arial", 16))
label.pack(pady=20)
# Function to update the label's text
def update_text():
current_text = dynamic_text.get()
dynamic_text.set(f"{current_text} π")
# Create a button to trigger the text update
button = tk.Button(root, text="Update Text", command=update_text)
button.pack(pady=10)
# Run the application
root.mainloop()
Comments
Post a Comment
hello