python tkinter 文本框控制台输出总是在最后一行?

python tkinter textbox console output to be always in last line?

我有这个文本框:

t_outputbox = tk.Text(tab_console, width=99, height=18, font='Tahoma 12',bg='#051da3', fg='#d9d9d9', relief="flat", highlightthickness=1, borderwidth=1)

并使用函数将所有控制台输出打印到它:

def redirector(inputStr): # send all prints to GUI instead of console
t_outputbox.config(state=NORMAL)
t_outputbox.insert(INSERT, inputStr)
t_outputbox.see(END)
t_outputbox.config(state=DISABLED)

并在我的代码的 ned 处使用此命令激活 stdout 以使用 redirector() 进行写入。

但有时,当我点击我的控制台并上下滚动时,它确实会在中间某处打印,而不是在文本框的末尾。

是否有解决办法,使新的印刷品始终位于盒子的末端?

sys.stdout.write=redirector

因为你在INSERT的位置后面插入了文字。这里,INSERT表示光标的位置。如果您想在文本小部件的末尾插入文本,则需要将 INSERT 替换为 END

def redirector(inputStr): # send all prints to GUI instead of console
    t_outputbox.config(state=NORMAL)
    t_outputbox.insert(END, inputStr)
    t_outputbox.see(END)
    t_outputbox.config(state=DISABLED)