In this tutorial, we are going to explore the Tkinter, the standard GUI library for Python, provides a variety of properties to customize widgets, making it a powerful tool for creating desktop applications. One common requirement when working with labels is to dynamically update the text displayed on them based on variables. This tutorial will guide you through the process of creating a Tkinter label with dynamic text.
Pre-requisite:
Import the Tkinter library into your environment using:
import tkinter as tk
Steps to Get Label Text with Variables:
- Start by creating an instance of the Tkinter window using ‘tk.Tk()’. This window will serve as the main application window.
- Use the ‘tk.Label’ widget to create a label. You can set various properties like text, background color, foreground color, font, and more.
- To change the text displayed by the label based on a variable, you can use the ‘StringVar’ class. This class allows you to bind a variable to the label so that changes to the variable automatically update the label.
- Add the label to the Tkinter window using the ‘pack’ method. You can also adjust the padding and other properties for a better visual appearance.
- Start the Tkinter event loop using ‘mainloop()’ to display the window and allow user interaction.
Method to Get Label Text
Code:
import tkinter as tk newWindow = tk.Tk() newWindow.geometry("600x300") mylabel = tk.Label(text = "Welcome to CodeSpeedy", background="Black", foreground="White", font=("Times New Roman",20,"bold italic"), relief="sunken", borderwidth=5, padx=20, pady=10) print("Label text: ", mylabel.cget("text")) mylabel.pack() newWindow.mainloop()
Here, ‘cget’ method stands for “configure get” and is used to query the current value of a specified configuration option of a widget. This can be particularly useful when you need to retrieve the text from a label widget, either for debugging or to use it in your application logic.
Output:
Label text: Welcome to CodeSpeedy
Note: Instead of using the ‘cget’ method, you can also retrieve the label text using a dictionary-style approach with the label object’s attributes. Simply access the ‘text’ property directly from the label instance to get the current text value.
import tkinter as tk newWindow = tk.Tk() newWindow.geometry("600x300") mylabel = tk.Label(text = "Welcome to CodeSpeedy", background="Black", foreground="White", font=("Times New Roman",20,"bold italic"), relief="sunken", borderwidth=5, padx=20, pady=10) print("Label text: ", mylabel["text"]) mylabel.pack() newWindow.mainloop()
Output:
Label text: Welcome to CodeSpeedy