How to trace Tkinter variables in Python

There is no built-in method in Python to track variables. But tkinter supports the creation of variable wrappers, which can be achieved by attaching the "observer" callback to the variable. The tkinter.Variable class has BooleanVar, DoubleVar, IntVarand StringVar and other constructors, which are used for Boolean values, double-precision floating-point values, integers, and strings, respectively. All of these can be registered to an observer, each time the value of the variable is triggered Will be triggered to visit. The observer remains active until it is explicitly deleted. It is also important to note that the callback function associated with the observer takes three parameters by default, namely the name of the Tkinter variable, the index of the tkinter variable (if it is an array, otherwise an empty string) and the access mode.

In Python 3.5 and 2.7 above older methods such as trace_variable()trace()trace_vdelete () and trace_vinfo() are replaced by the below mentioned methods.

  1. trace_add (): The trace_add () method has replaced trace_variable() method. The trace_add() method is used to add an observer to a variable and returns the name of the callback function whenever the value is accessed.

 

Syntax : trace_remove(self, mode, callback_name)

Parameters:
Mode: It is one of “array”, “read”, “write”, “unset”, or a list or tuple of such strings.
callback_name: It is the name of the callback function to be registered on the tkinter variable.

3. trace_info():  The trace_info() method has replaced trace_vinfo() method and trace() method. It returns the name of the callback. This is generally used to find the name of the callback that is to be deleted. This method takes no argument other than the tkinter variable itself.

Syntax : trace_info(self) 

To better understand the importance of the above methods, let us take an example and build a simple widget. Although using a Tkinter variable as a textvariable automatically updates the widget every time the variable changes, sometimes developers may want to do some extra processing when reading or modifying (or changing) the variable. This is where variable tracking comes in. Our callback function will be triggered every time the text in the widget changes, and return a string "Variable Changed".

 

# Python program to trace
# variable in tkinter


from tkinter import *


root = Tk()

my_var = StringVar()

# defining the callback function (observer)
def my_callback(var, indx, mode):
	print ("Traced variable {}".format(my_var.get())

# registering the observer
my_var.trace_add('write', my_callback)

Label(root, textvariable = my_var).pack(padx = 5, pady = 5)

Entry(root, textvariable = my_var).pack(padx = 5, pady = 5)

root.mainloop()

Let’s see the code in action where the trace_add() method registers an observer which gets triggered every time the textvariable in the widget changes.

Submit Your Programming Assignment Details