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

Phi*_*erg 9 python qt tkinter qt4 ipython

我编写了以下类,用于在额外窗口中生成"监视"输出.

  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()
Run Code Online (Sandbox Code Playgroud)

用法:

Monitor.write("Hello World!")
Run Code Online (Sandbox Code Playgroud)

Ale*_*lli 29

cls.text.see(Tkinter.END)在一个调用插入后面添加一个语句.

  • 这样做时考虑可用性.例如,如果用户从底部向上滚动以查看您不想自动滚动的内容. (3认同)

Jon*_*ott 6

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

def callback():
    text.see(END)
    text.edit_modified(0)
text.bind('<<Modified>>', callback)
Run Code Online (Sandbox Code Playgroud)

请小心。正如@BryanOakley 指出的,Modified 虚拟事件仅被调用一次,直到被重置。考虑如下:

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()
Run Code Online (Sandbox Code Playgroud)

  • 您是否知道“&lt;&lt;Modified&gt;&gt;”仅在窗口第一次从未修改转换为已修改时触发一次?在使用“.edit_modified(True)”清除该标志之前,您不会再次收到该事件。 (3认同)