4
votes

I am making a Python (3) GUI Program with tkinter, and I am using a redirect function to direct all my print statements to a GUI Scrolled text box.

This is the redirect function (in the same class as the tkinter window):

def redirector(self,inputStr):
    self.txt.insert(tk.INSERT, inputStr)
    self.txt.update()
    self.txt.see(tk.END)

And then I add this line when I want to start redirecting the output:

sys.stdout.write = self.redirector

But when I rename the file to .pyw, nothing appears on the textbox. Please suggest a method to correctly direct the text to the GUI Window.

1
you mean it works when you call your file .py right? - Jean-François Fabre
@Jean-FrançoisFabre Yes it does. - Nikhil Ramakrishnan
Please revised answer. - bzrr

1 Answers

2
votes

The reason why your print calls aren't working is because when you run a .pyw file on Windows, the executable that runs your program is actually pythonw.exe, which internally initializes your application by calling WinMain(), and so doesn't create a console. No console means no standard IO streams, thus sys.stdout is undefined.

Instead, I suggest you subclass tk.Text and define the write() and flush() functions as instance methods. Then all you have to do is set sys.stdout to your subclass instance and everything should work.

import sys
import tkinter as tk


class TextOut(tk.Text):

    def write(self, s):
        self.insert(tk.CURRENT, s)

    def flush(self):
        pass


if __name__ == '__main__':
    root = tk.Tk()
    text = TextOut(root)
    sys.stdout = text
    text.pack(expand=True, fill=tk.BOTH)
    root.mainloop()