Issue with Redirecting stdout to Tkinter text widget with threads Issue with Redirecting stdout to Tkinter text widget with threads tkinter tkinter

Issue with Redirecting stdout to Tkinter text widget with threads


I tinkered around the idea and found two ways to make it work.

1) Your approach works even if it is not thread safe. Only problem seems to be that the application needs to be initialized before printing to the widget starts. If you would like to start the second thread "immediately" and not from some callback, this works for me:

root.after(100, thread1.start)

2) Second and more clean approach is based at example linked by @falsetru . However it requires you to print to stdout by reasonable speed so updates would not choke on it.

from Tkinter import *import threadingimport Queue # This is thread safeimport timeclass Std_redirector():    def __init__(self, widget):        self.widget = widget    def write(self,string):        self.widget.write(string)class ThreadSafeText(Text):    def __init__(self, master, **options):        Text.__init__(self, master, **options)        self.queue = Queue.Queue()        self.update_me()    def write(self, line):        self.queue.put(line)    def update_me(self):        while not self.queue.empty():            line = self.queue.get_nowait()            self.insert(END, line)            self.see(END)            self.update_idletasks()        self.after(10, self.update_me)def func():    i = 0    while True:        i += 1        print i        time.sleep(0.01)root = Tk()text = ThreadSafeText(root)text.pack()sys.stdout = Std_redirector(text)thread1 = threading.Thread(target=func)thread1.start()root.mainloop()

Based on my experience from other GUI toolkits I wanted to use root.after_idle() but it did not work as I have expected it to.