Here's a more comcrete example, that 'adapts' a tk text widget into a Python file onject. It then replaces sys.stdout using this class, and demonstrates that 'print' still works.
import Tkinter as tk
import sys
class TkWriteFile:
def __init__(self, text):
self._text = text
self.closed = 0
self.mode = 'w'
self.softspace = 0
def write(self, data):
if self.closed:
raise ValueError('I/O operation on closed TkFile')
self._text.insert('end', data)
def writelines(self, lines):
self.write(''.join(lines))
def close(self):
self.closed = 1
mw = tk.Tk()
t = tk.Text(mw)
t.pack()
sys.stdout = TkWriteFile(t)
print 'spam'
mw.mainloop()