且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将标准输出重定向到 Tkinter 文本小部件

更新时间:2023-01-06 18:51:36

问题是当你调用app.mainloop()时,线程正忙于执行Tkinter主循环,所以之前的语句在退出循环之前它不会被执行.但是一旦退出主循环,您尝试使用 Text 小部件,但它已经被销毁了.

The problem is that when you call app.mainloop(), the thread is busy executing the Tkinter mainloop, so the statements before it are not executed until you exit the loop. But once you exit the mainloop, you try to use the Text widget but it is already destroyed.

我建议您将对 main 的调用移动到 Tkinter 小部件的回调(我想您已经尝试使用 app.button_press() 来做到这一点),因此可以使用 Text 对象来显示文本.

I recommend you to move the call to main to the callback of a Tkinter widget (I suppose you are already trying to do that with app.button_press()), so the Text object can be used to display the text.

class CoreGUI(object):
    def __init__(self,parent):
        self.parent = parent
        self.InitUI()
        button = Button(self.parent, text="Start", command=self.main)
        button.grid(column=0, row=1, columnspan=2)

    def main(self):
        print('whatever')

    def InitUI(self):
        self.text_box = Text(self.parent, wrap='word', height = 11, width=50)
        self.text_box.grid(column=0, row=0, columnspan = 2, sticky='NSWE', padx=5, pady=5)
        sys.stdout = StdoutRedirector(self.text_box)


root = Tk()
gui = CoreGUI(root)
root.mainloop()