redirect stdout to tkinter text widget

前端 未结 2 1325
孤城傲影
孤城傲影 2020-12-19 23:48

I\'m trying to redirect the stdout of a function to a tkinter text widget. The problem I am running into is that it writes each line to a new window instead of listing every

2条回答
  •  青春惊慌失措
    2020-12-20 00:00

    The above solution is very complete; I was able to essentially copy and paste it into my code with only one small modification. I'm not entirely sure why, but the StdoutRedirector requires a flush method.

    I'm guessing it's because sys.stdout calls a flush() method when it exits, but I'm haven't waded into the docs deep enough to actually understand what that means.

    Running the above code in the Jupyter environment caused the code to hang indefinitely until the kernel was restarted. The console kicks the following errors:

    sys.stdout.flush()
    AttributeError: 'StdoutRedirector' object has no attribute 'flush'
    ERROR:tornado.general:Uncaught exception, closing connection.
    

    The simple solution is to make a small change to the StdoutRedirector class by adding a flush method.

    class StdoutRedirector(IORedirector):
        '''A class for redirecting stdout to this Text widget.'''
    
        def write(self,str):
            self.text_area.insert("end", str)
        def flush(self):
            pass
    

    Thanks to the giants that came before me and offered this very clear explanation.

提交回复
热议问题