2
votes

First time using Tkinter and I'm trying to make a widget that displays text from a text file and updates the widget when the text in the file changes. I can get a widget to read from a text file, but I can't seem to make it update when the text changes.

Here's the code I'm using right now:

 from 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 for help on updating widgets but I can only find help with updating when a button is pressed or an entry widget is used. I was thinking of using a loop that goes through every minute, but wouldn't that just keep creating new widgets?

1

1 Answers

3
votes

So you are only reading from file once in your example. As you suggest you need to add some kind of loop to enable you to reread the file often. The problem with normal loops in Tkinter is that they are run in the main thread, making your GUI unresponsive. To get around this, use the Tkinter's after method.

The after method schedules a function to be run after N milliseconds. For example:

from Tkinter import *

# This function will be run every N milliseconds
def get_text(root,val,name):
    # try to open the file and set the value of val to its contents 
    try:
        with open(name,"r") as f:
            val.set(f.read())
    except IOError as e:
        print e
    else:
        # schedule the function to be 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 will loop until the GUI is closed.