如何在Tkinter消息窗口中自动滚动
我写了一个类,用来在一个额外的窗口中显示“监控”输出。
- 可惜的是,它没有自动滚动到最新的一行。哪里出了问题呢?
- 我在使用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 个回答
6
对于那些想尝试绑定的人:
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()
42
在调用插入内容的那行代码后面,添加一行代码 cls.text.see(Tkinter.END)
。