Tkinger variable trace() using w mode
After understanding the variable settings in the Tkinter Variable get() and set() section, we can use the variable settings to track the widget control and have the program execute a callback function when its contents change.
Tkinger variable trace() using w mode Example#1
Designed to output apidemos.com
in the Python Shell window when the content of the Widget control Entry changes.
from tkinter import *
def callback(*args): # If it is def callback(): then an error will occur
print("data changed: ",xE.get()) # Output the current content at the command line
root = Tk()
root.title("apidemos.com") # Title of the window
xE = StringVar() # Variable content of Entry
entry = Entry(root,textvariable=xE)
entry.pack(pady=5,padx=10)
xE.trace("w",callback) # Execute callback if there is a change
root.mainloop()
Output:
When you see the output of the above window, you can also see the following output in the Python Shell window at the same time.
The focus of the above procedure is line 12, which reads as follows.
xE.trace("w",callback) # Execute callback if there is a change
The first parameter above is the mode, w means when there is an execution write, it automatically goes to execute the callback function. You can also take your own function name, and this action is called change tracking. We can use the xE variable category to track when the contents of a Widget control change to perform a specific action, in this case outputting the contents of an Entry in a Python Shell window. Another focus of the above program is line 4, which reads as follows.
def callback(*args):
The meaning of the *args
parameter above will be explained in a later lesson.
Tkinger variable trace() using w mode Example#2
Expand the above example and also create a Label control below the Entry control, so that when there is input in the Entry, it is displayed in the Label control below.
from tkinter import *
def callback(*args): # If it is def callback(): then an error will occur
xL.set(xE.get())
print("data changed: ",xE.get()) # Output the current content at the command line
root = Tk()
root.title("apidemos.com") # Title of the window
xE = StringVar() # Variable content of Entry
entry = Entry(root,textvariable=xE)
entry.pack(pady=5,padx=10)
xE.trace("w",callback) # Execute callback if there is a change
xL = StringVar()
label = Label(root,textvariable=xL)
xL.set("Synchronized display")
label.pack(pady=5,padx=10)
root.mainloop()
Output:
When you see the output of the above window, you can also see the following output in the Python Shell window.