ARTICLE AD BOX
I am very, very new to programming having just finished a semester-long course on Python. I wanted to take an existing program I had written for my class and redirect all the output text to a separate window instead of the program terminal. I followed a tutorial, but I'm having issues with actually getting the output text to the created window. Both programs run fine separately, but just aren't connected.
I was thinking the issue was that my original program involves user input, thus when running the full program, the original program must complete first in the terminal and then the window will open (still blank).
This is the code I had written while following the tutorial linked above:
import tkinter as tk from tkinter import scrolledtext import sys import io class TextWidgetStream(io.TextIOBase): def __init__(self, text_widget, tag="stdout"): super().__init__() self.text_widget = text_widget self.tag = tag # Tag for coloring def write(self, s): self.text_widget.after(0, self._insert_text, s) def _insert_text(self, s): self.text_widget.config(state='normal') self.text_widget.insert('end', s, (self.tag,)) self.text_widget.see('end') #Auto-scroll to bottom self.text_widget.config(state='disabled') def flush(self): pass #Required for stream compliance class OutputRedirectorGUI: def __init__(self, root): self.root = root self.root.title("Title") self.root.geometry("800x600") #Save original Streams self.original_stdout = sys.stdout self.original_stderr = sys.stderr #Create and configure Text widget w/ scrollbar self.text_widget = scrolledtext.ScrolledText( root, wrap=tk.WORD, state=tk.DISABLED, bg="#020501", font=("Good Old DOS", 15) ) self.text_widget.pack(padx=10, pady=10, fill = "both", expand=True) #Configure tags for stdout(black) & stderr (red) self.text_widget.tag_configure("stdout", foreground = "green4") self.text_widget.tag_configure("stderr", foreground = "red") # Redirect stdout and stderr: self.stdout_redirector = TextWidgetStream(self.text_widget, tag="stdout") self.stderr_redirector = TextWidgetStream(self.text_widget, tag="stderr") sys.stdout = self.stdout_redirector sys.stderr = self.stderr_redirector #Restore streams on exit self.root.protocol("WM_DELETE_WINDOW", self.on_exit) def on_exit(self): #Restore original streams before closing sys.stdout = self.original_stdout sys.stderr = self.original_stderr self.root.destroy()After this, my original program essentially is just a def main() function, with a while loop that runs through various print & input statements until finished. After that code is this:
if __name__ == "__main__": main() root = tk.Tk() app = OutputRedirectorGUI(root) root.mainloop()Being very new to this i'm kind of just going by trial and error when following tutorials.
