How to set Tkinter Label text through variables

In this tutorial, we will learn how to change or set Label text through variables in Tkinter.

We can do this in two different ways, and I will show you both of those. But among those, I will recommend performing one method and will also explain why you should choose that.

First method: Directly using a variable in the text parameter of Tkinter

We can directly put a string variable in the text parameter just like this:

import tkinter as tk
newWindow = tk.Tk()
newWindow.geometry("800x800")
myVar = "Hi I am a variable"
myLabel = tk.Label(text=myVar)
myLabel.pack()
newWindow.mainloop()

Output:

Set Tkinter Label Text from variable

But in this case, you must declare the variable before creating the Label, otherwise, it will not work.

Like you can not do this at all:

myLabel = tk.Label(text=myVar)
myVar = "Hi I am a variable"

Set Label Text in Tkinter using StringVar

I will recommend this method, as Tkinter is specially providing you with another parameter for your Label. That is textvariable.

Let’s understand how we can do this through an example:

import tkinter as tk
newWindow = tk.Tk()
newWindow.geometry("800x800")
myVar = tk.StringVar()
myVar.set("Hello I am from StringVar")
myLabel = tk.Label(textvariable=myVar)
myLabel.pack()
newWindow.mainloop()

Output:

Set Label Text in Tkinter using StringVar

 

Note: Do not forget to use textvariable parameter in the Label. If you use text parameter, it will not work.

Why I am recommending using StringVar?

Because you don’t have to set the string in the variable before creating the Label. You can also set it later on like this:

myVar = tk.StringVar()
myLabel = tk.Label(textvariable=myVar)
myVar.set("Hello I am from StringVar")

It will also give you the same output.

You can check this:

Change Tkinter window size with variables – Dynamic

Leave a Reply

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