tags:

views:

41

answers:

1

Hi,

How can I redirect stdout data to a tkinter Text widget?

Much obliged,

Dennis

+3  A: 

You need to make a file-like class whose write method writes to the Tkinter widget instead, and then do sys.stdout = <your new class>. See this question.

Example (copied from the link):

class IORedirector(object):
    '''A general class for redirecting I/O to this Text widget.'''
    def __init__(self,text_area):
        self.text_area = text_area

class StdoutRedirector(IORedirector):
    '''A class for redirecting stdout to this Text widget.'''
    def write(self,str):
        self.text_area.write(str,False)

and then, in your Tkinter widget:

# To start redirecting stdout:
import sys
sys.stdout = StdoutRedirector( self )
# (where self refers to the widget)

# To stop redirecting stdout:
sys.stdout = sys.__stdout__
katrielalex
Hi! Could you maybe provide me with an example? I'm very new with python and I'm struggling to get this to work. Much obliged :)
FLX
The linked question has all the code you need, I think. You need to make your own version of the class `StdoutRedirector` as is done there, then set `sys.stdout = StdoutRedirector`. I'll copy the code into my answer.
katrielalex