I'm making a simple GUI for an app that performs some slow calculations. I though about adding something similar to a console so I could display messages informing about the execution of program. Since I'm working with Tkinter
, I've figure I would add a text box and redirect the standard output to it, which in principle was pretty neat. However, when I press the button that starts the calculations, the interface halts completely, and the text box is only updated when the calculations are finished, which defeats the purpose of this console.
Is there a way not to halt the window and actually update the text live?
Here is a minimal working example of the problem:
from tkinter import *
import math, sys
class StdoutRedirector(object):
def __init__(self, text_widget):
self.text_space = text_widget
def write(self, string):
self.text_space.insert('end', string)
self.text_space.see('end')
def slowprint():
print("First line")
aaa = math.factorial(300000)
print("Second line")
bbb = math.factorial(300000)
print("Third line")
window = Tk()
text_box = Text(window, wrap='word')
text_box.grid(columnspan=5, row=1, sticky='nswe', padx=5, pady=5)
sys.stdout = StdoutRedirector(text_box)
Button(window,text='Print', command=slowprint).grid(padx=5, pady=5)
When the button is pressed, the window halts, then all messages are printed at once. It would be nice if it was possible to print each message when the print
function is actually called.