Changing the Tkinter label text

Tkinter label widgets can display text or a picture on the screen. You can use only one typeface on a label. It is possible to have many lines of text. For instance, a label can include any text, and a window can have numerous labels (just like any widget can be displayed multiple times in a window).

The label text attribute in Python Tkinter allows you to change/update the label text easily. Another technique to edit the Tkinter label text is to change the label’s text property. In this lesson, we’ll look at changing label text in Tkinter Python using more than one approach.

Tkinter is a python module that provides a standard GUI (Graphical user interface). It allows you to quickly and easily create a graphical user interface (GUI) application.

To make a tkinter application, follow these steps:

  • First import the module — tkinter
  • Make the primary window (container)
  • Add as many widgets as you want to the main window.
  • Apply the Trigger event to the widgets.

Widgets are the command and control elements of any graphical user interface (GUI) application. The primary purpose of this widget is to provide a wide range of controls. Buttons, labels, text boxes, and many other widgets are examples. Importing tkinter is similar to importing any other Python package. The module’s name in Python 2.x is ‘Tkinter,’ but in Python 3.x, it is ‘tkinter.’

import tkinter

When establishing a Python application with GUI, there are two primary approaches that the user must remember.

Tk(screenName=None, baseName=None, className=’Tk’, useTk=1):

Tkinter provides the method Tk(screenName=None, baseName=None, className=’Tk’, useTk=1) for creating a main window. You can replace the className with the desired name to change the window’s name. The following is the basic code used to generate the application’s primary window:

m=tkinter.Tk()

where m is the main window object’s name

mainloop():

When your application is ready to run, you call the mainloop() method. mainloop() is an infinite loop that runs the application, waits for an event and processes the event as long as the window is open.

m.mainloop()
m.mainloop()

import tkinter
m = tkinter.Tk()
'''
It is the region where widgets are added.
'''
m.mainloop()

Tkinter also provides access to the widgets’ geometric configuration, which you can use to organize widgets in parent windows. There are three types of geometry manager classes.

  • pack() method: It arranges the widgets into blocks before placing the widgets in the parent widget.
  • grid() method: Before placing the widgets in the parent widget, it organizes them in a grid (table-like structure).
  • The method place(): It arranges the widgets by placing them in the program’s specified locations.

The label is one of its widgets, and it’s in charge of creating a display box area for text and graphics. Let’s first explore the Tkinter label widget.

Python Tkinter – Label

Python provides many alternatives for creating a graphical user interface (Graphical User Interface). Further, Tkinter is the most widely used GUI technique out of all the options. It’s a standard Python interface to the Python-supplied Tk GUI toolkit. Python with Tkinter is the quickest and most straightforward approach to constructing graphical user interfaces.

Using widgets, creating a GUI with Tkinter is simple. Widgets, such as buttons and menus, are standard graphical user interface (GUI) elements. Now, let’s look at how to update the label’s text:

The Label Widget

Tkinter Label is a widget that allows you to create display boxes with text or graphics. The developer can change the text displayed by this widget at any moment. You can also use it to execute operations like underlining text and spanning text across numerous lines. It’s vital to remember that a label can only display text in one typeface at a time. To utilize a label, you have to tell it what to display (this can be text, a bitmap, or an image).

The syntax is as follows:

w = Label ( master, option, … )

The master parameter represents the parent window.

Parameters

  • master: This is the window’s parent.
  • Options: The format of the widget can be changed using various settings. The most commonly used options for this widget are listed below. These options can be used as comma-separated key-value pairs:

The following are a few options:

anchor: If the widget has more space than required for the text, this option is used to manage the alignment of the text. anchor=CENTER is the default, which centered the text in the available space.

bg: This option changes the background color behind the label and indicator.

height: This option is used to specify the new frame’s vertical dimension.

width: The label’s width in characters (not pixels!). If this option is not selected, the label is scaled to fit its contents.

bd: This option is used to control the size of the indicator’s border. Also, the default bd value is 2 pixels.

font: If you’re using the text or textvariable options to show text in the label, the font option is used to select the typeface displayed in the text.

cursor: When the mouse is moved over the label, it is used to designate which cursor should be displayed. The standard cursor is used by default.

bitmap: It is used to set the bitmap to the provided graphical object so that the label can represent graphics rather than text.

fg: Text and bitmap labels use the label clear. The operating system determines the default.
It is the color that will appear at the place of the 1-bits in a bitmap if it is displayed.

image: In the label widget, this option displays a static image.

padx: This option adds extra spaces between the text on the label’s left and right sides. This option has a default value of 1.

pady: This option adds extra space between the label’s top and bottom text. This option has a default value of 1.

Justify: This option is used to specify how many lines of text should be aligned. Use the values LEFT, RIGHT, or CENTER. It’s worth noting that the anchor option is used to position the text within the widget. CENTER is the default setting for justify.

relief: The appearance of a decorative border around the label is controlled by this option. FLAT is the default setting for this parameter.

underline: This

wraplength: Instead of having a single line for the label text, it can be split across multiple lines, each with the number of characters indicated in this option.

from tkinter import *


top = Tk()
top.geometry("450x300")
	
# email's label
user_email = Label(top, text = "Email").place(x = 40,	y = 60)
	
# the label for user_password
user_password = Label(top,	text = "Password").place(x = 40, y = 100)
	
submit_button = Button(top,	text = "Submit").place(x = 40, y = 130)
	There are number of options which are used to change the format of the widget.
user_email_input_area = Entry(top,	width = 30).place(x = 110, y = 60)
	
user_password_entry_area = Entry(top, width = 30).place(x = 110, y = 100)
	
top.mainloop()

Example: using a Label in Tkinter

from tkinter import *
root = Tk()
w = Label(root, text='Codeunderscored.com!')
w.pack()
root.mainloop()

Now, let’s look at how to update the label’s text:

Using Label.config() method

The syntax for Label.config() is as follows:

Label.config(text)

Parameter: text– The text to display in the label.

This method is used to do a label widget overwriting.

Example:

importing everything from tkinter
from tkinter import *

# creating the tkinter window
Main_window = Tk()

# variable
my_text = "Codeunderscored updated !!!"

# function define for
# updating the my_label
# widget content
def counter():

	# use global variable
	global my_text
	
	# configure
	my_label.config(text = my_text)

# create a button widget and attached
# with counter function
my_button = Button(Main_window,
				text = "Please update",
				command = counter)

# create a Label widget
my_label = Label(Main_window, text = "Codeunderscored")

# place the widgets
# in the gui window
my_label.pack()
my_button.pack()

# Start the GUI
Main_window.mainloop()

Using StringVar() class

StringVar is a type of Tkinter constructor that creates a string variable in Tkinter. Tkinter will update this particular widget when the StringVar variable is adjusted when we pair it with the Tkinter widgets.

The syntax for StringVar() is as follows:

StringVar()

Return: String variable object

This class is used to set and change values per the requirements.

Example 1 : Using StringVar() class

# importing everything from tkinter
from tkinter import *

# create gui window
Main_window = Tk()

# set the configuration
# of the window
Main_window.geometry("220x100")

# define a function
# for setting the new text
def java():
	my_string_var.set("You must go with Java")

# define a function
# for setting the new text
def python():
	my_string_var.set("You must go with Python")



# create a Button widget and attached
# with java function
btn_1 = Button(Main_window,
			text = "I love Android",
			command = java)

# create a Button widget and attached
# with python function
btn_2 = Button(Main_window,
			text = "I love Machine Learning",
			command = python)

# create a StringVar class
my_string_var = StringVar()

# set the text
my_string_var.set("What should I learn")

# create a label widget
my_label = Label(Main_window,
				textvariable = my_string_var)


# place widgets into
# the gui window
btn_1.pack()
btn_2.pack()
my_label.pack()

# Start the GUI
Main_window.mainloop()

Example 2: Using StringVar() class

import tkinter as tk

class Test():
    def __init__(self):
        self.root = tk.Tk()
        self.text = tk.StringVar()
        self.text.set("Test")
        self.label = tk.Label(self.root, textvariable=self.text)

        self.button = tk.Button(self.root,
                                text="Click to change text below",
                                command=self.changeText)
        self.button.pack()
        self.label.pack()
        self.root.mainloop()

    def changeText(self):
        self.text.set("Text updated")        

app=Test()


self.text = tk.StringVar()
self.text.set("Code Test")

The string variable could not be started by the Tkinter constructor using the string.

self.text = tk.StringVar()

To set the StringVar value, we should use the set method, such as self.text.set (“Test”).

self.label = tk.Label(self.root, textvariable=self.text)

By setting textvariable to self.text associates the StringVar variable self.text with the label widget self.label. If self.text is changed, the Tk toolkit starts tracking the changes and updates the text self.label. A Tkinter dynamic label is created with the code above. When the self.text is changed, it immediately displays the Tkinter label text.

Use the label text property to change/update the Python Tkinter Label Text

Changing the label’s text property is another way to change the Tkinter label text.

import tkinter as tk

class Test():
    def __init__(self):
        self.root = tk.Tk()
        self.label = tk.Label(self.root, text="Text")

        self.button = tk.Button(self.root,
                                text="Click to change text below",
                                command=self.changeText)
        self.button.pack()
        self.label.pack()
        self.root.mainloop()

    def changeText(self):
        self.label['text'] = "Text updated"        

app=Test()     

The text of the label object can be started with text=”Text” and altered by setting a new value to the text key of the label object. We may alternatively use the tk.Label.configure() method to update the text property, as seen below. The above codes function in the same way.

import tkinter as tk

class Test():
    def __init__(self):
        self.root = tk.Tk()
        self.label = tk.Label(self.root, text="Text")

        self.button = tk.Button(self.root,
                                text="Click to change text below",
                                command=self.changeText)
        self.button.pack()
        self.label.pack()
        self.root.mainloop()

    def changeText(self):
        self.label.configure(text="Text Updated")        

app=Test()      

You can update the text of the label widget using a button and a function if you need to tweak or change it dynamically.

# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame or window
tk_win = Tk()

# Set the size of the tkinter window
tk_win.geometry("700x350")

# Define a function update the label text
def on_click():
   label["text"] = "Code in Python"
   b["state"] = "disabled"

# Create a label widget
label = Label(tk_win, text="Code: Click the Button to update this Text",
font=('Calibri 15 bold'))
label.pack(pady=20)

# Create a button to update the label widget
b = Button(tk_win, text="Update Label", command=on_click)
b.pack(pady=20)

tk_win.mainloop()

Output

update the text of the label widget using a button and a function
update the text of the label widget using a button and a function

When you run the code above, a label text and a button will appear in the window. The label text will only be updated when you click the button.

after clicking on "Update Label"
after clicking on “Update Label”

Example: font configuration

Some Tk widgets, such as the label, text, and canvas widgets, allow you to choose the typefaces used to display text. A “font” configuration option is commonly used to accomplish this. It’s crucial to keep in mind that typefaces are a few areas that aren’t platform-independent. The attribute “fg” is used to modify the color of the text. On the other hand, the attribute “bg,” can be used to change the label’s background color.

import tkinter as tk
rt = tk.Tk()
tk.Label(rt,
         text="Codeunderscored: Red Text in displayed in Times Font",
         fg = "red",
         font = "Times").pack()
tk.Label(rt,
         text="Codeunderscored: Green Text in displayed in Helvetica Font",
         fg = "dark green",
         bg = "light green",
         font = "Helvetica 12 bold italic").pack()
rt.mainloop()

Conclusion

Tkinter Label widgets are commonly used in applications to show text or images. Using the config(**options) method, we can change the label widget’s text property, color, background, and foreground colors. If you need to adjust or change the text of the label widget dynamically, you can use a button and a function to do so.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *