Non-blocking print redirection to Tkinter text widget

90 Views Asked by At

I've been able to get print statements redirected to a Tkinter text widget based on the answer to this question. It describes a class to redirect stdout:

class TextRedirector(object):
    def __init__(self, widget, tag="stdout"):
        self.widget = widget
        self.tag = tag

    def write(self, str):
        self.widget.configure(state="normal")
        self.widget.insert("end", str, (self.tag,))
        self.widget.configure(state="disabled")

Utilizing the TextRedirector class, I have the following code

import sys
import time
from tkinter import *

root = Tk()
t = Text(root, width = 20, height = 5)
t.grid()

old_stdout = sys.stdout
sys.stdout = TextRedirector(t)

for i in range(5):
    print i + 1
    time.sleep(1)

sys.stdout = old_stdout

However, this solution seems to be blocking (the text shows up all at once once the for-loop ends).

I have successfully put together a non-blocking solution using Popen and threading, but this isn't an ideal solution due to some unrelated constraints.

Is there a way to have the print statements show up in the text box in real-time?

0

There are 0 best solutions below