Tracing Tkinter variables

When you specify a Tkinter variable, such as textvariable, for a widget (textvariable = myvar), the widget automatically gets updated whenever the value of the variable changes. However, there might be times when, in addition to updating the widget, you need to do some extra processing at the time of reading or writing (or modifying) the variable.

Tkinter provides a method to attach a callback method that will be triggered every time the value of a variable is accessed. Thus, the callback acts as a variable observer. 

The callback creation method is named trace_variable(self, mode, callback) or simply trace(self, mode, callback).

The mode argument can take a value of r, w, or u, which stand for read, write, or undefined. Depending upon the mode specifications, the callback method is triggered when the variable is read or written.

By default, the callback method gets three arguments. The arguments, in order of their position, are as follows:

  • The name of the Tkinter variable
  • The index of the variable in case the Tkinter variable is an array, otherwise, it's an empty string
  • The access modes (r, w, or u)

Note that the triggered callback function may also modify the value of the variable. However, this modification does not trigger additional callbacks. 

Let's look at an example of variable tracing in Tkinter. Take a look at how a change in a traced Tkinter variable triggers a callback (see code 10.01_trace_variable.py):

from tkinter import Tk, Label, Entry, StringVar
root = Tk()
my_variable = StringVar()

def trace_when_my_variable_written(var, indx, mode):
print ("Traced variable {}".format(my_variable.get()))

my_variable.trace_variable("w", trace_when_my_variable_written)

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

root.mainloop()

The following line of code attaches a callback to trace the variable:

my_variable.trace_variable("w", trace_when_my_variable_written)

Now, every time you write in the entry widget, it modifies the value of my_variable. Because we have set a trace on my_variable, it triggers the callback method that, in our example, simply prints the new value into the console, as shown in the following screenshot:

The trace on a variable is active until it is explicitly deleted. You can delete a trace using the following command:

trace_vdelete(self, mode, callback_to_be_deleted)

The trace method returns the ID and name of the callback method. This can be used to get the name of the callback method that needs to be deleted.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.170.223