Python Forum
[Tkinter] Redirecting stdout to TextBox in realtime
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] Redirecting stdout to TextBox in realtime
#3
Since you are already writing to a file, it is easy to open that file and write the contents to your textbox. As Gribouillis mentions, use after() to periodically call a function that reads from the file and writes to the display.

If the file is a stopgap measure and you would rather redirect stdout, use redirect_stdout from the contextlib module.
from contextlib import redirect_stdout, redirect_stderr
…
class Console(QtWidgets.QWidget):
    """A GUI version of code.InteractiveConsole."""
...
    def errorwrite(self, line):
        """Buffer stdout until you get a newline"""
        self.stdoutbuffer += line
        if self.stdoutbuffer [-1] == '\n':
            # Add line to display
            self.writeoutput(self.stdoutbuffer[:-1])
            self.stdoutbuffer = ''

    def writeoutput(self, line):
        """Display line in outdisplay"""
        self.outdisplay.moveCursor(QtGui.QTextCursor.End)
        self.outdisplay.appendPlainText(line)
        self.outdisplay.moveCursor(QtGui.QTextCursor.End)
...
    # Redirect stdout to console.write
    with redirect_stdout(console):
        console.show() # draws the window
        sys.exit(app.exec_()) # Like mainloop in tk
This is from a embeddable console I use in Qt applications. Most of it should be applicable to Tk other than the mechanics of how the text is appended to the text widget (I use QPlainTextEdit widget to display stdout).
Reply


Messages In This Thread
RE: Redirecting stdout to TextBox in realtime - by deanhystad - Jun-06-2020, 11:05 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  recording textbox data into a variable paul18fr 4 468 Feb-19-2024, 09:30 PM
Last Post: Axel_Erfurt
  [Tkinter] TkInter Realtime calculation marlonsmachado 3 1,141 Oct-28-2022, 02:02 AM
Last Post: deanhystad
  [Tkinter] Redirecting all print statements from all functions inside a class to Tkinter Anan 1 2,672 Apr-24-2021, 08:57 AM
Last Post: ndc85430
  [Tkinter] Tkinter Textbox only showing one character Xylianth 1 2,197 Jan-29-2021, 02:59 AM
Last Post: Xylianth
  tkinter how to unselect text in textbox Battant 0 2,283 Feb-17-2020, 02:00 PM
Last Post: Battant
  [Tkinter] cannot type in textbox msteffes 2 3,017 Jul-28-2018, 04:20 AM
Last Post: msteffes
  GUI insert textbox value into a Class dimvord 0 2,269 Jul-04-2018, 06:49 PM
Last Post: dimvord

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020