【问题标题】:How to scroll automatically within a Tkinter message window如何在 Tkinter 消息窗口中自动滚动
【发布时间】:2010-10-23 03:07:01
【问题描述】:

我编写了以下类,用于在一个额外的窗口中生成“监控”输出。

  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!")

【问题讨论】:

    标签: python qt qt4 tkinter ipython


    【解决方案1】:

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

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

    【讨论】:

    • 为什么说它坏了?这是一个记录在案的错误吗?
    • 您是否知道&lt;&lt;Modified&gt;&gt; 仅在窗口第一次从未修改转换为已修改时触发?在您使用.edit_modified(True) 清除该标志之前,您将无法再次获得该事件。
    • 数字:tkdocs 没有解释这一点,effbot 也没有,但如果你仔细阅读,tcl.tk 会。调整上面的答案,谢谢!顺便说一句,它是.edit_modified(False)
    【解决方案2】:

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

    【讨论】:

    • 在执行此操作时要考虑可用性。例如,如果用户从底部向上滚动查看您不想自动滚动的内容。
    • "Python:如果用户不手动滚动,则自动将 ScrolledText 滚动到末尾"stackoverflow.com/questions/51781247/…
    猜你喜欢
    • 2010-12-29
    • 2017-07-19
    • 2021-09-17
    • 2020-09-10
    • 2014-03-01
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多