redirect stdout to tkinter text widget

前端 未结 2 1323
孤城傲影
孤城傲影 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:10

    The fix is simple: don't create more than one redirector. The whole point of the redirector is that you create it once, and then normal print statements will show up in that window.

    You'll need to make a couple of small changes to your redirector function. First, it shouldn't call Tk; instead, it should create an instance of Toplevel since a tkinter program must have exactly one root window. Second, you must pass a text widget to IORedirector since it needs to know the exact widget to write to.

    def redirector(inputStr=""):
        import sys
        root = Toplevel()
        T = Text(root)
        sys.stdout = StdoutRedirector(T)
        T.pack()
        T.insert(END, inputStr)
    

    Next, you should only call this function a single time. From then on, to have data appear in the window you would use a normal print statement.

    You can create it in the main block of code:

    win = Tk()
    ...
    r = redirector()
    win.mainloop()
    

    Next, you need to modify the write function, since it must write to the text widget:

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

    Finally, change your Zerok function to use print statements:

    def Zerok(): ... if os.stat(filename).st_size==0:
    print(filename) else: print("There are no empty files in that Directory") break

提交回复
热议问题