What are the arguments to Tkinter variable trace method callbacks?


Tkinter variable (var) is defined for a particular widget (textvariable=var) to store the updated value of a widget. Sometimes, there might be a case, while updating the variable information, we need to process some extra operations such as read, write, or undefined.

Tkinter provides a way to update the variable with a callback function trace (self, mode, callback) which takes the operation of the process such as read(r), write(w), or undefined(u). On the basis of these values, the callback decides what the process needs to do in the callback function. The other two values define the variable which needs to be traced (contains widget information) and the index of the variable.

Example

In this example, we will trace the value of the Entry widget that gets updated when the user enters a value in it.

#Import the required library
from tkinter import*
#Create an instance of Tkinter frame
win = Tk()
win.geometry("750x250")
#create a variable to store the User Input
my_variable = StringVar()
def trace_when_Entry_widget_is_updated(var, index, mode):
   print ("{}".format(my_variable.get()))

my_variable.trace_variable("w", trace_when_Entry_widget_is_updated)
Label(win, textvariable = my_variable).pack(padx=5, pady=5)
Entry(win, textvariable = my_variable, width=20).pack(ipadx=20,padx=5, pady=5)
win.mainloop()

Output

Executing the above code will display an Entry widget that stores the input in a variable. The callback function will trace the updated value of the variable and display it in a Label widget.

Now, type something in the given Entry widget. The label widget will mimic the input value and display the output on the window.

On the console, you will get to see the following −

H
He
Hel
Hell
Hello
Hello
Hello W
Hello Wo
Hello Wor
Hello Worl
Hello World

Updated on: 22-Apr-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements