Tkinter StringVar with Examples – Tkinter Tutorial

Tkinter StringVar()

Hello folks! In this tutorial, we will look at how to use StringVar function in Tkinter as a way to store text variables and to edit text in widgets. We will also see an example to write callbacks to notify when there is a change in the text variable. So let’s get started.

What is StringVar()?

Tkinter contains build-in programming types which work like a normal python variable with additional features used to manipulate values of widgets like Label and Entry more effectively, which makes them different from python data types. These variables also contain getter and setter methods to access and change their values. StringVar is an example of them.

A variable defined using StringVar() holds a string data where we can set text value and can retrieve it. Also, we can pass this variable to textvariable parameter for a widget like Entry. The widget will automatically get updated with the new value whenever the value of the StringVar() variable changes.

Defining a StringVar() variable

Here is what it takes to define a string variable using Tkinter StringVar():

  • master: It is a widget that the StringVar object is associated with. If nothing is specified, it defaults to the root window.
  • value: The initial value given to the string variable. Defaults to “”.
  • name: The name given to the defined variable. Default value is PY_VARnum(like PY_VAR1, PY_VAR2, etc).

For example, in the code below, we create a string variable using StringVar() and assign it to the textvariable parameter of Label widget.

import tkinter as tk

master_window = tk.Tk()
master_window.title("StringVar Example")

string_variable = tk.StringVar(master_window, "Hello Everyone!!")

label = tk.Label(master_window, textvariable=string_variable, height=150)

Defining StringVar
Defining StringVar

Setting values of StringVar() variables

Values can be assigned to string variables defined using StringVar() using 2 ways:

  • Passing the value in constructor: You can pass the value of the string variable in value parameter of the constructor while defining the Tkinter variable.
string_variable = tk.StringVar(master=master_window, value="Initial value of string variable")
  • Using the set() method: You can use set() method to change the value of the string. For example:
string_variable = tk.StringVar(master_window)
string_variable.set("Some Text")

Retrieving values of StringVar() variables

We can use get() method on StringVar() variable to retrieve the text value present in the variable.

import tkinter as tk

master_window = tk.Tk()

string_variable = tk.StringVar(master_window)
string_variable.set("Welcome to AskPython!!")


Using this way, we can also retrieve the data present in the Entry widget when StringVar variable is passed to the widget. For example:

import tkinter as tk

master_window = tk.Tk()
master_window.title("StringVar get() example")

def print_data():

string_variable = tk.StringVar(master_window)

label = tk.Label(master_window, text="Enter Data: ")
label.grid(row=0, column=0)

entry = tk.Entry(master_window, textvariable=string_variable)
entry.grid(row=0, column=1)

button = tk.Button(master_window, text="Print data", command=print_data)
button.grid(row=1, column=0, columnspan=2)


Writing callbacks to trace the StringVar() variables

One interesting feature of Tkinter-defined objects is that the object will be notified whenever its value is changed, read, or deleted. This feature is helpful if you want to update other widgets automatically in case of some operation on Tkinter-defined objects.

To define a callback on StringVar() object, we can use trace() method on the StringVar() object that takes 2 parameters:

  • mode: The type of operation on the StringVar() object.
    • 'w' (write): invoke callback when value is changed
    • 'r' (read): invoke callback when value is read
    • 'u' (unset): invoke callback when value is deleted
  • callback: method to call when there is an operation on the object.

Let’s consider an example where a greeting message will be generated for the name entered in the Entry widget. As we change the data in the StringVar() object through Entry widget, a method will be called that will change the greeting message simultaneously.

import tkinter as tk

class GreetingApp(tk.Tk):
    def __init__(self):
        self.title('Greeting Application')

        self.name_var = tk.StringVar()
        self.name_var.trace('w', self.create_greeting_message)

    def create_widgets(self):
        self.description_label = tk.Label(self, text="Enter your name:")
        self.description_label.grid(column=0, row=0)

        self.entry = tk.Entry(self, textvariable=self.name_var)
        self.entry.grid(column=1, row=0)

        self.greeting_label = tk.Label(self)
        self.greeting_label.grid(column=0, row=1, columnspan=2)
    def create_greeting_message(self, *args):
        name_entered = self.name_var.get()

        greeting_message = ""
        if name_entered != "":
            greeting_message = "Hello " + name_entered
        self.greeting_label['text'] = greeting_message

if __name__ == "__main__":
    app = GreetingApp()

Here is the result:

StringVar() Greeting Example


In this tutorial, we learned about StringVar() in Tkinter and how to use it to set the string value, retrieve it and writing callbacks that automatically changes the data.

Thanks for reading!!