How to do stuff when a variable's value is modified?
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
def do_stuff():
demo['text'] = var
if __name__ == '__main__':
root = tk.Tk()
var = "Value"
demo = tk.Label(root, text=var)
demo.pack()
var = "New Value" # call do_stuff()
tk.mainloop()
For example, I want to call do_stuff whenever var is modified.
One way would be to make use of Variable classes(
BooleanVar,DoubleVar,IntVar,StringVar,Variable), and theirtrace_addmethod. Which allows to call a method when the value the instance holds is modified.Also further note that, while not always practical, some widgets have variable options(variable, textvariable, listvariable) that allows the value they hold to be in sync with that of a Variable class object. Below example makes use of that:
Another way would be to make use of attribute assignment magic method(
__setattr__) of an object, when working with classes.For example the
demolabel will be updated each timeself.stringattribute is modified: