python - Tkinter label widget not updating when text file changes -
first time using tkinter , i'm trying make widget displays text text file , updates widget when text in file changes. can widget read text file, can't seem make update when text changes.
here's code i'm using right now:
tkinter import * root = tk() root.minsize(740,400) file = open("file location") eins = stringvar() data1 = label(root, textvariable=eins) data1.config(font=('times', 37)) data1.pack() eins.set(file.readline()) root.mainloop()
i've searched on updating widgets can find updating when button pressed or entry widget used. thinking of using loop goes through every minute, wouldn't keep creating new widgets?
so reading file once in example. suggest need add kind of loop enable reread file often. problem normal loops in tkinter run in main thread, making gui unresponsive. around this, use tkinter's after
method.
the after
method schedules function run after n milliseconds. example:
from tkinter import * # function run every n milliseconds def get_text(root,val,name): # try open file , set value of val contents try: open(name,"r") f: val.set(f.read()) except ioerror e: print e else: # schedule function run again after 1000 milliseconds root.after(1000,lambda:get_text(root,val,name)) root = tk() root.minsize(740,400) eins = stringvar() data1 = label(root, textvariable=eins) data1.config(font=('times', 37)) data1.pack() get_text(root,eins,"test.txt") root.mainloop()
this loop until gui closed.
Comments
Post a Comment