1

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?

detroitwilly
  • 811
  • 3
  • 16
  • 30
  • The redirector isn't what's blocking. `time.sleep(1)` does exactly what it says - it puts the whole UI to sleep. – Bryan Oakley Apr 16 '21 at 19:41
  • Understood. Thanks for that. Turns out this is pretty much a duplicate of [this question](https://stackoverflow.com/questions/14710529/how-to-redirect-in-real-time-stdout-from-imported-module-to-tkinter-text-widget?rq=1). – detroitwilly Apr 16 '21 at 19:43

0 Answers0