Python Tkinter StringVar(): set(), get(), textvariable and trace_add()


Tkinter StringVar flow between variable and widgets

What Is StringVar()? 🔝

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.

Syntax of StringVar() 🔝

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')

Using StringVar with Entry and Label 🔝

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.

Dynamic GUI Updates with StringVar in Python Tkinter

set() and get() Methods 🔝

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.

Changing a Label Using set()

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.

Initializing StringVar() 🔝

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.

Resetting StringVar() 🔝

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.

Finding the Length of a StringVar 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

Normal Python Variable vs StringVar() 🔝

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.

Monitoring Changes with trace_add() 🔝

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())

Example: Run a Function When StringVar Changes

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().

Output in the console:
Welcome
Tkinter StringVar() get(), set() and trace_add() Methods

trace_add() Modes 🔝

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().

Removing a Trace with trace_remove() 🔝

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.

Live Character Count with StringVar() 🔝

Tkinter StringVar trace_add example counting characters

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.

One StringVar for Entry, Label and Button 🔝

Common Tkinter StringVar used by Label Button and Entry widgets

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.

Updating Random Text on a Label 🔝

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.

Common StringVar() Mistakes 🔝

1. Using text Instead of textvariable

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
)

2. Reading the StringVar Without get()

To retrieve the stored string value, use:

value=str1.get()

Use the StringVar object itself for widget options such as textvariable.

3. Forgetting Callback Arguments with trace_add()

A trace callback receives arguments from Tkinter. A simple way to accept them is:

def my_callback(*args):
    print(str1.get())

4. Creating StringVar Before the Tkinter Root

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)

5. Using trace_add() When textvariable Is Enough

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.

Summary of StringVar() 🔝

  • StringVar() is a Tkinter variable class for string values.
  • Use textvariable to connect a StringVar to widgets such as Entry, Label, and Button.
  • set() changes the stored value.
  • get() returns the current value.
  • An initial value can be supplied with value=.
  • Use set("") to reset the value to an empty string.
  • len() can count the characters returned by get().
  • Widgets sharing one StringVar can stay synchronized automatically.
  • 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.
  • Use trace_add() when variable changes must trigger additional program logic.

Practice Questions 🔝

Change Background Color Based on Character Count

Interlinked Combobox Using Variable Changes

DoubleVar() IntVar() BooleanVar()




Subscribe to our YouTube Channel here



plus2net.com



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




Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer