I am trying to redirect stdout into a Tkinter Text widget in real time using Python 2.7.2 on Windows 7. In my code below, I intended to have a print statement appear in the Text widget every 2 seconds. What happens, instead, is that all 3 lines
Received sleep-command
Going to sleep for 2 s
Just woke up
appear simultaneously as soon as both sleep() and mod1.main() have been evaluated.
Surprisingly (to me, at least) the problem disappears when I do not redirect stdout. That is, if I comment out the line
sys.stdout = StdoutRedirector(outputPanel)
IDLE displays the print statements in real time. Can somebody explain this to me and suggest a way to get around it? Thanks in advance!
Here is my example code:
mod1.py
import time
import sys
def main():
print('Going to sleep for 2 s')
time.sleep(2)
print('Just woke up')
text_GUI.py
from Tkinter import *
import sys
import time
import mod1
old_stdout = sys.stdout
class StdoutRedirector(object):
def __init__(self, text_area):
self.text_area = text_area
def write(self, str):
self.text_area.insert(END, str)
self.text_area.see(END)
def sleep():
print('Received sleep-command')
time.sleep(2)
mod1.main()
root = Tk()
# Textbox
outputPanel = Text(root, wrap='word', height = 11, width=50)
outputPanel.grid(column=0, row=0, columnspan = 2, sticky='NSWE', padx=5, pady=5)
sys.stdout = StdoutRedirector(outputPanel)
# Sleep button
sleepBtn = Button(root, text='Sleep', command=sleep)
sleepBtn.grid(row=1, column=1, sticky='E', padx=5, pady=5)
root.mainloop()
sys.stdout = old_stdout