How to run a code whenever a Tkinter widget value changes?

I think the correct method is to use trace on a tkinter variable that has been assigned to a widget.

For example…

import tkinter

root = tkinter.Tk()
myvar = tkinter.StringVar()
myvar.set('')
mywidget = tkinter.Entry(root,textvariable=myvar,width=10)
mywidget.pack()

def oddblue(a,b,c):
    if len(myvar.get())%2 == 0:
        mywidget.config(bg='red')
    else:
        mywidget.config(bg='blue')
    mywidget.update_idletasks()

myvar.trace('w',oddblue)

root.mainloop()

The w in trace tells tkinter whenever somebody writes (updates) the variable, which would happen every time someone wrote something in the Entry widget, do oddblue. The trace always passes three values to whatever function you’ve listed, so you’ll need to expect them in your function, hence a,b,c. I usually do nothing with them as everything I need is defined locally anyway. From what I can tell a is the variable object, b is blank (not sure why), and c is the trace mode (i.e.w).

For more info on tkinter variables check this out.

Leave a Comment