如何在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!")
解决方案
在一次调用插入后立即添加语句 cls.text.see(Tkinter.END)
。
其他提示
对于那些可能想要尝试绑定的人:
def callback():
text.see(END)
text.edit_modified(0)
text.bind('<<Modified>>', callback)
小心点。正如@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()
不隶属于 StackOverflow