python - Tracing a list with Tkinter -
tkinter has these variable classes: booleanvar
, doublevar
, intvar
, stringvar
. of them have trace()
method allows attach callback called when variable changes.
is possible (or there workaround) trace list? specifically, i'm looking way monitor list can change elements of treeview.
the code below includes test function (forcechange) can deleted, demonstrates rest of code traces python list variable. since you're using tk event loop, used that, i've tested using sched , time modules schedule events when there no gui.
from tkinter import * import sys class listmanager: def __init__(self, root, listvar): self.root = root self.listvar = listvar self.previous_value = listvar.copy() # create event watch changes list. self.watch_event = root.after(20, self.watchlist) # create event change list. test purposes only. self.change_event = root.after(200, self.forcechange) def watchlist(self): ''' compare previous list current list. if differ, print message (or else). ''' try: if self.previous_value != self.listvar: print("changed! was:", self.previous_value, " is:", self.listvar) self.previous_value = self.listvar.copy() # reschedule function continue check. self.root.after(20, self.watchlist) except exception: print("variable has been destroyed") self.root.after_cancel(self.change_event) def forcechange(self): try: next = self.listvar[-1:][0] except: # variable destroyed. return if next == 11: sys.exit() next += 1 self.listvar.append(next) self.root.after(500, self.forcechange) if __name__ == '__main__': root = tk() # list we'll watch. mylist = [1, 2, 3] # create list manager vlist = listmanager(root, mylist) root.mainloop()
Comments
Post a Comment