Printing stdout (print) commands to tkinter window with .pyw extension
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 sysimport tkinter as tkclass TextOut(tk.Text): def write(self, s): self.insert(tk.CURRENT, s) def flush(self): passif __name__ == '__main__': root = tk.Tk() text = TextOut(root) sys.stdout = text text.pack(expand=True, fill=tk.BOTH) root.mainloop()