python 如何在 Tkinter 消息窗口内自动滚动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/811532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to scroll automatically within a Tkinter message window
提问by Philipp der Rautenberg
I wrote the following class for producing "monitoring" output within an extra window.
我编写了以下类,用于在额外的窗口中生成“监视”输出。
- Unfortunately it doesn't scroll automatically down to the most recent line. What is wrong?
- As I also have problems with Tkinter and ipython: how would an equivalent implementation with qt4 look like?
- 不幸的是,它不会自动向下滚动到最近的一行。怎么了?
- 因为我也有 Tkinter 和 ipython 的问题:qt4 的等效实现会是什么样子?
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!")
回答by Alex Martelli
Add a statement cls.text.see(Tkinter.END)
right after the one calling insert.
cls.text.see(Tkinter.END)
在调用 insert 后立即添加一条语句。
回答by Jonathan Abbott
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:
小心点。正如@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()