Tkinter variable trace() using r mode
Tkinger variable trace() using w mode We introduced tracing and executing specific functions when the content of a widget control is changed, but we can also design tracing and executing specific functions when the content of a control is read.
Tkinter variable trace() using r mode Example#1
Add a Read
button so that the Python Shell window will not display data when entering data in Entry, but the Label below will be displayed simultaneously. The main function is that if the Read
button is clicked, the system will warn that the data has been read and output the read data.
from tkinter import *
def callbackW(*args): # Executed when the content is changed
# xE.get()
xL.set(xE.get()) # Change label content
def callbackR(*args): # Executed when the content is read
print("Warning:Data is read!")
def hit(): # Read data
print("Read the data:",xE.get())
# print("Type is:",type(xE.get())) # The type is: <class 'str'>
# print("Read the data2:",xE.get())
# print("Read the data3:",xE.get())
# 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) # Set the Label content to the variable x
entry.pack(pady=5,padx=10)
xE.trace("w",callbackW) # If there is a change execute callbackW
xE.trace("r",callbackR) # If it has been read execute callbackR
xL = StringVar() # Label's variable content
label = Label(root,textvariable=xL)
xL.set("Synchronized display")
label.pack(pady=5,padx=10)
btn = Button(root,text="Read",command=hit) # Create "Read" button
btn.pack(pady=5)
root.mainloop()
Output:
If you click the Read
button, you can see the following execution results in the Python Shell window.
The focus of the above procedure is line 28, which reads as follows.
xE.trace("r",callbackR) # If it has been read execute callbackR
The first parameter above is the mode, and r represents the callbackR function that automatically goes to execute when a read is executed. You can also take your own function name, and this action is called read tracking. We can use the xE variable category to track the specific action performed when the content of the widget control is read, in this case the Python Shell window outputs "Warning: data read!" and the contents of the Entry.