How to redirecting "stdout" to a Label widget?
label, python, stdout, tkinter
Solution
The reason you are not seeing the text set is that it is set correctly for a split second and then immediately set to blank. This is because print is sending a newline to stdout after the print statements. Here is a modified version that appends to the Label rather than overwrite it for every print statement.
class StdoutRedirector(IORedirector):
def write(self,str):
self.TEXT_INFO.config(text=self.TEXT_INFO.cget('text') + str)
Problem
I am trying to redirect stdout to a Label widget. The goal is to "print" into the Label all the Python prints that are in my script. But when I click on `BUTTON1` nothing happens... Here is my code: ``` from Tkinter import * import sys import tkMessageBox class App: def __init__(self, master): self.frame = Frame(master, borderwidth=5, relief=RIDGE) self.frame.grid() class IORedirector(object): def __init__(self,TEXT_INFO): self.TEXT_INFO = TEXT_INFO class StdoutRedirector(IORedirector): def write(self,str): self.TEXT_INFO.config(text=str) self.TEXT_HEADER = self.text_intro = Label(self.frame, bg="lightblue",text="MY SUPER PROGRAMM") ## HEADER TEXT self.TEXT_HEADER.grid(row=0, column=0, columnspan=2, sticky=W+E+N+S) self.MENU = Frame(self.frame, borderwidth=5, relief=RIDGE, height=12) self.MENU.grid(row=1, column=0, sticky=N) self.button = Button(self.MENU, text="QUIT", fg="red", bg="red", command=self.frame.quit) self.button.grid(row=4, column=0) self.BUTTON1 = Button(self.MENU, text="BUTTON1", command=self.BUTTON1_CMD) self.BUTTON1.grid(row=0, column=0,sticky=W+E) self.TEXT_INFO = Label(self.frame, height=12, width=40, text="I WANT TO SEE THE STDOUT OUTPUT HERE", bg="grey",borderwidth=5, relief=RIDGE) self.TEXT_INFO.grid(row=1, column=1) sys.stdout = StdoutRedirector(self.TEXT_INFO) def BUTTON1_CMD(self): print "TEST NUMBER ONE" print "TEST NUMBER TWO" root = Tk() app = App(root) root.mainloop() ```