StringVar() is a Tkinter variable class used to store and manage string values in a GUI application.
A StringVar can be connected to widgets such as
Entry,
Label, and
Button through their textvariable option.
When the value stored in the StringVar changes, widgets connected to the same variable can update automatically.
A StringVar also provides methods such as set(), get(), and trace_add() for changing, reading, and monitoring its value.
str1=tk.StringVar(master, value, name)
All three arguments are optional.
master - the Tkinter parent associated with the variable.value - the initial value stored in the variable.name - an optional Tcl variable name.A common declaration is:
str1=tk.StringVar(my_w)
We can also supply an initial value:
str1=tk.StringVar(my_w, value='Hello')
One of the most common uses of StringVar() is connecting the same value to multiple Tkinter widgets.
In this example, an Entry and a
Label share the same StringVar. As text is entered in the Entry widget, the Label updates automatically.
import tkinter as tk
my_w=tk.Tk()
my_w.geometry("500x250")
my_w.title("plus2net.com")
my_str=tk.StringVar(my_w)
e1=tk.Entry(
my_w,
textvariable=my_str,
font=("Arial", 18)
)
e1.grid(row=0, column=0, padx=20, pady=30)
l1=tk.Label(
my_w,
textvariable=my_str,
font=("Arial", 18),
bg="lightgreen",
width=20
)
l1.grid(row=1, column=0, padx=20, pady=10)
e1.focus_set()
my_w.mainloop()
Both widgets use:
textvariable=my_str
Because they share the same Tkinter variable, the Entry and Label remain synchronized. We do not need trace_add() just to keep these two widgets synchronized.
The set() method assigns a value to a StringVar. The get() method returns its current value.
import tkinter as tk
my_w=tk.Tk()
str1=tk.StringVar(my_w)
str1.set('Hello')
print(str1.get())
my_w.destroy()
Output
Hello
Use set() when the value needs to be changed from Python code. Use get() when the current value needs to be read.
import tkinter as tk
my_w=tk.Tk()
my_w.geometry("300x180")
str1=tk.StringVar(my_w, value='Hello')
l1=tk.Label(
my_w,
textvariable=str1,
font=("Arial", 20)
)
l1.grid(row=0, column=0, padx=20, pady=20)
b1=tk.Button(
my_w,
text='Update',
command=lambda: str1.set('Welcome')
)
b1.grid(row=1, column=0)
my_w.mainloop()
Clicking the button calls str1.set('Welcome'). Because the Label uses textvariable=str1, its displayed text changes automatically.
A value can be assigned after creating the variable:
str1=tk.StringVar(my_w)
str1.set('Option 1')
We can also assign the initial value while creating the variable:
str1=tk.StringVar(
my_w,
value='Option 1'
)
Both approaches store 'Option 1' in str1.
To clear the current text stored in a StringVar, set its value to an empty string.
str1.set("")
Any widget connected through textvariable=str1 will also display the updated empty value.
The value returned by get() is a string, so the
len() function can count its characters.
str1.set('Python')
length=len(str1.get())
print(length)
Output
6
A normal Python string variable stores text:
name='Alex'
A Tkinter StringVar also stores a string value, but it is designed to communicate with Tkinter widgets.
name=tk.StringVar(
my_w,
value='Alex'
)
The important difference is that a StringVar can be connected to a widget using textvariable, and its changes can be monitored using trace_add().
For example, an Entry widget can update a StringVar while the user types. A callback can then check the new value and perform another action, such as displaying the number of characters entered.
The trace_add() method attaches a callback function to a Tkinter variable. The callback can run when the variable is read, written, or unset.
The most frequently used mode is 'write', which runs the callback whenever the variable value changes.
callback_id=str1.trace_add('write', my_callback)
The callback function receives information from Tkinter. Using *args allows the function to accept those callback arguments.
def my_callback(*args):
print(str1.get())
import tkinter as tk
my_w=tk.Tk()
my_w.geometry("300x180")
my_w.title("plus2net.com")
str1=tk.StringVar(
my_w,
value='Hello'
)
def my_r(*args):
print(str1.get())
l1=tk.Label(
my_w,
textvariable=str1,
width=15
)
l1.grid(row=0, column=0, padx=20, pady=20)
b1=tk.Button(
my_w,
text='Update',
command=lambda: str1.set('Welcome')
)
b1.grid(row=1, column=0)
str1.trace_add('write', my_r)
my_w.mainloop()
When the button changes str1 from 'Hello' to 'Welcome', the write trace runs my_r().
Welcome
trace_add() is useful when changing a Tkinter variable should trigger additional Python code.
The common trace modes are:
'write' - runs when the variable value is changed.'read' - runs when the variable value is read.'unset' - runs when the underlying Tkinter variable is removed.
For most GUI input monitoring, 'write' is the most useful mode.
str1.trace_add(
'write',
my_callback
)
More than one mode can also be monitored by the same callback.
str1.trace_add(
('write', 'read'),
my_callback
)
Older Tkinter code may use trace(). For new code on this page, we use trace_add().
The value returned by trace_add() identifies the registered callback. We can use that value with trace_remove() when the callback is no longer required.
callback_id=str1.trace_add(
'write',
my_callback
)
# Remove the write trace later
str1.trace_remove(
'write',
callback_id
)
After the trace is removed, changing str1 will no longer call that registered callback.
A practical use of trace_add() is displaying the number of characters entered by the user.
The Entry widget uses textvariable=e1_str. Whenever the text changes, the 'write' trace runs my_upd().
import tkinter as tk
my_w=tk.Tk()
my_w.geometry("450x160")
my_w.title("plus2net.com")
e1_str=tk.StringVar(my_w)
e1=tk.Entry(
my_w,
textvariable=e1_str,
bg='yellow',
font=('Arial', 22)
)
e1.grid(
row=0,
column=0,
padx=10,
pady=30
)
l1=tk.Label(
my_w,
text='0',
font=('Arial', 22)
)
l1.grid(
row=0,
column=1,
padx=10
)
def my_upd(*args):
length=len(e1_str.get())
l1.config(text=str(length))
e1_str.trace_add(
'write',
my_upd
)
my_w.mainloop()
The len() function counts the characters in the string returned by e1_str.get(). The Label is updated after every change.
The same StringVar can be used by multiple widgets.
In this example, the Entry, Label, and Button all use str1. Changing the Entry updates the shared variable. Clicking the button changes the same variable using set().
import tkinter as tk
my_w=tk.Tk()
my_w.geometry("550x220")
my_w.title("plus2net.com")
str1=tk.StringVar(
my_w,
value='Hello'
)
l1=tk.Label(
my_w,
textvariable=str1,
width=15,
font=('Arial', 18),
bg='yellow'
)
l1.grid(
row=0,
column=0,
padx=10,
pady=30
)
e1=tk.Entry(
my_w,
textvariable=str1,
font=('Arial', 18)
)
e1.grid(
row=0,
column=1,
padx=10
)
b1=tk.Button(
my_w,
textvariable=str1,
command=lambda: str1.set('Welcome')
)
b1.grid(
row=1,
column=0,
columnspan=2,
pady=10
)
my_w.mainloop()
All three widgets refer to the same Tkinter variable, so changes to str1 can be reflected across the connected widgets.
A StringVar can also be updated repeatedly from Python code.
This example selects a random value from a list and displays it on a Label. The Tkinter after() method calls the function again after a delay.
import tkinter as tk
import random
my_w=tk.Tk()
my_w.geometry("300x200")
my_w.title("plus2net.com")
str1=tk.StringVar(
my_w,
value='Random List'
)
my_list=[
'King',
'Queen',
'Jack',
'Ronald',
'Ram',
'Tina',
'Vik'
]
l1=tk.Label(
my_w,
textvariable=str1,
width=15,
bg='yellow',
font=('Arial', 22)
)
l1.grid(
row=0,
column=0,
padx=30,
pady=50
)
def my_fun():
random_element=random.choice(my_list)
str1.set(random_element)
my_w.after(1000, my_fun)
my_fun()
my_w.mainloop()
Every second, choice() selects another list item and set() updates the Label through the shared StringVar.
This uses the current value only:
l1=tk.Label(
my_w,
text=str1.get()
)
If you want the widget to remain connected to the StringVar, use:
l1=tk.Label(
my_w,
textvariable=str1
)
To retrieve the stored string value, use:
value=str1.get()
Use the StringVar object itself for widget options such as textvariable.
A trace callback receives arguments from Tkinter. A simple way to accept them is:
def my_callback(*args):
print(str1.get())
A clear beginner-friendly pattern is to create the Tkinter root first and then associate the variable with that root.
my_w=tk.Tk()
str1=tk.StringVar(my_w)
If an Entry and Label only need to display the same value, connecting both widgets to the same StringVar is enough.
Use trace_add() when a value change must run additional Python logic.
StringVar() is a Tkinter variable class for string values.textvariable to connect a StringVar to widgets such as Entry, Label, and Button.set() changes the stored value.get() returns the current value.value=.set("") to reset the value to an empty string.len() can count the characters returned by get().trace_add('write', callback) can run a function whenever the value changes.read, write, and unset are available trace modes.trace_remove() can remove a previously registered trace callback.trace_add() when variable changes must trigger additional program logic.StringVar() in Tkinter?StringVar() associated with a Tkinter root window?textvariable option?set() and get()?StringVar()?StringVar?StringVar synchronize an Entry and Label?trace_add('write', callback) do?*args?trace_add() necessary instead of only using textvariable?StringVar?Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
22-03-2021 | |
| Very bad to call a variable in Python "str" str = tk.StringVar(my_w) # declare StringVar() because str is build-in method to stringify data! class str(object='') --> built-in function in Python | |
23-03-2021 | |
| Thanks, Let us use str1 | |