如何在Tkinter消息窗口中实现自动滚动

16

我编写了下面的类来在额外窗口中生成“监视”输出。

  1. 不幸的是,它不会自动滚动到最近的一行。有什么问题吗?
  2. 由于我也遇到了Tkinter和ipython的问题:使用qt4实现等效的实现将是什么样子?

这是代码:

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()

用法:

Monitor.write("Hello World!")
2个回答

41
在调用insert语句后添加一条语句cls.text.see(Tkinter.END)

4
在进行此操作时,请考虑可用性。例如,如果用户从底部向上滚动查看某些内容,您不想自动滚动。 - Bryan Oakley
Python:如果用户没有手动滚动,则自动将ScrolledText滚动到末尾 - Brent

5

对于那些想尝试绑定的人:

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

请注意,正如@BryanOakley指出的那样,修改后的虚拟事件只会在重置之前被调用一次。请考虑以下内容:

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()

你为什么说它坏了?这是一个已记录的错误吗? - Bryan Oakley
3
您知道<<Modified>>事件仅在窗口第一次从未修改变为已修改时触发吗?在使用.edit_modified(True)清除标志之前,您将不会再次收到此事件。 - Bryan Oakley
数字:tkdocs没有解释这个,也没有effbot,但是如果你仔细阅读tcl.tk,它就有了。调整上面的答案,谢谢!顺便说一句,应该是.edit_modified(False) - Jonathan Abbott

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接