How to scroll automatically within a Tkinter message window


Question

I wrote the following class for producing "monitoring" output within an extra window.

  1. Unfortunately it doesn't scroll automatically down to the most recent line. What is wrong?
  2. As I also have problems with Tkinter and ipython: how would an equivalent implementation with qt4 look like?

Here is the code:

import Tkinter
class Monitor(object):
  @classmethod
  def write(cls, s):
    try:
      cls.text.insert(Tkinter.END, str(s) + "\n")
      cls.text.update()
    except Tkinter.TclError, e:
      print str(s)
  mw = Tkinter.Tk()
  mw.title("Message Window by my Software")
  text = Tkinter.Text(mw, width = 80, height = 10)
  text.pack()

Usage:

Monitor.write("Hello World!")
1
9
3/18/2017 1:13:24 PM

Accepted Answer

Add a statement cls.text.see(Tkinter.END) right after the one calling insert.

29
5/1/2009 2:50:48 PM

To those who might want to try binding:

def callback():
    text.see(END)
    text.edit_modified(0)
text.bind('<<Modified>>', callback)

Just be careful. As @BryanOakley pointed out, the Modified virtual event is only called once until it is reset. Consider below:

import Tkinter as tk

def showEnd(event):
    text.see(tk.END)
    text.edit_modified(0) #IMPORTANT - or <<Modified>> will not be called later.

if __name__ == '__main__':

    root= tk.Tk()

    text=tk.Text(root, wrap=tk.WORD, height=5)
    text.insert(tk.END, "Can\nThis\nShow\nThe\nEnd\nor\nam\nI\nmissing\nsomething")
    text.edit_modified(0) #IMPORTANT - or <<Modified>> will not be called later.
    text.pack()
    text.bind('<<Modified>>',showEnd)

    button=tk.Button(text='Show End',command = lambda : text.see(tk.END))
    button.pack()
    root.mainloop()

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon