Tkinter: callback or copycat function… ( trace StringVar )

After having shown some little ‘apps’ that does something useful lately, we want to go back revisiting some code about tkinter widgets that do something useful but not for a practical goal, so that we can use these knowledge for other more complex projects. Today we are going to take a look at the trace method to ‘follow’ what the user is writing in an entry widget.

To trace the value of your input could be useful sometimes. That is what this code does. There is a function called trace that will be deprecated. In this code you can get what the user are inserting in an entry widget and, as he types, a label will copy that value and show it immediately in its text.

from tkinter import *

def copycat(sv, lb):
    lb['text'] = sv.get()

def labentry():
	sv = StringVar() # Create the StringVar
	sv.trace("w", lambda name, index, mode, sv=sv: copycat(sv, lb))
	# copycat is usually called callback
	e = Entry(root, textvariable=sv)
	lb = Label(root, text = "")
	lb.pack()
	e.pack()
	e.focus()

root = Tk()
labentry() # => create label and entry
root.mainloop()

 

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.