Search code examples
pythontkinterconsoletextboxstdout

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


I have this textbox:

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

And use a function to print all console output to it:

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)

And use this commadn at the ned of my code to activate stdout to use redirector() to write.

But sometimes, when I click into my console, and scroll up and down, it does print in the middle somewehere and not at the end of the textbox.

Is there a fix for that so that new prints are forced to always beat the end of the box?

sys.stdout.write=redirector

Solution

  • It is because you are inserting text after the position of INSERT. Here, INSERT means the position of cursor. If you want to insert text at the end of the text widget then you need to replace INSERT with 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)