problems with tkinter updates

Peter Otten __peter__ at web.de
Tue Jan 24 04:52:52 EST 2012


yves at zioup.com wrote:

> 
> I'm missing something about tkinter updates. How can I give tkinter a
> chance to run?
> 
> Here's some code:
> 
> import time
> import tkinter
> import tkinter.scrolledtext
> 
> tk = tkinter.Tk()
> f = tkinter.Toplevel(tk)
> st = tkinter.scrolledtext.ScrolledText(f)
> st.pack()
> 
> 
> 
> def update():
>      print('updating')
>      st.see(tkinter.END)
>      tk.after(1000, update)
> 
> 
> input('hit enter to start')
> update()
> f = open('/etc/services')
> 
> for line in f:
>    st.insert(tkinter.END, line + '\n')
>    print('got it')
>    #time.sleep(5)
>    input('more?')
> 
> input('finished?')
> 
> 
> 
> 
> When I do this (input('more?'), it works as expected. If I comment that
> line out, then the program reads the entire file, then update the window
> right at the end, even if I put a sleep in there. What can I do inside the
> loop to give tk a chance?

Have update() (renamed to read_more() in my code) do the reading:

import sys
import tkinter
import tkinter.scrolledtext

root = tkinter.Tk()

text_window = tkinter.Toplevel()
text = tkinter.scrolledtext.ScrolledText(text_window)
text.pack()

infile = open(sys.argv[1])

def read_more():
    line = next(infile, None)
    if line is not None:
        text.insert(tkinter.END, line)
        root.after(100, read_more)
    else:
        text.insert(tkinter.END, "\nThat's all folks", "looney")
        text.tag_configure("looney", foreground="RED")
    text.see(tkinter.END)

read_more()
root.mainloop()





More information about the Python-list mailing list