How to change the Tkinter label text?
Prerequisites: Introduction to tkinter
Tkinter is a standard GUI (Graphical user interface) package for python. It provides a fast and easy way of creating a GUI application.
To create a tkinter application:
- Importing the module — tkinter
- Create the main window (container)
- Add any number of widgets to the main window.
- Apply the event Trigger on the widgets.
Widgets are the controlling tools for any GUI application. Here widget’s main role is to provide a good variety of control. Some widgets are buttons, labels, text boxes, and many more.
One of its widgets is the label, which is responsible for implementing a display box-section for text and images. Click here For knowing more about the Tkinter label widget.
Now, let’ see how To change the text of the label:
Method 1: Using Label.config() method.
Syntax: Label.config(text)
Parameter: text– The text to display in the label.
This method is used for performing an overwriting over label widget.
Example:
Python3
from tkinter import *
Main_window = Tk()
my_text = "GeeksforGeeks updated !!!"
def counter():
global my_text
my_label.config(text = my_text)
my_button = Button(Main_window,
text = "Please update" ,
command = counter)
my_label = Label(Main_window,
text = "geeksforgeeks" )
my_label.pack()
my_button.pack()
Main_window.mainloop()
|
Output:
Method 2: Using StringVar() class.
Syntax: StringVar()
Return: String variable object
This class is used for setting the values and changing it according to the requirements.
Python3
from tkinter import *
Main_window = Tk()
Main_window.geometry( "220x100" )
def java():
my_string_var. set ( "You must go with Java" )
def python():
my_string_var. set ( "You must go with Python" )
btn_1 = Button(Main_window,
text = "I love Android" ,
command = java)
btn_2 = Button(Main_window,
text = "I love Machine Learning" ,
command = python)
my_string_var = StringVar()
my_string_var. set ( "What should I learn" )
my_label = Label(Main_window,
textvariable = my_string_var)
btn_1.pack()
btn_2.pack()
my_label.pack()
Main_window.mainloop()
|
Last Updated :
17 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...