在Python文本框中自动滚动文本和滚动条

Ds *_*jun 6 python tkinter

我有一个tkinter'Text'和'Scrollbar'正常工作.在我的文本窗口程序中,自动行将继续添加.因此,当插入新的文本行并且数据超出限制时,我希望文本和滚动条自动滚动到底部,以便始终显示最新的文本行.这该怎么做?

另外如何链接文本窗口和滚动条的滚动,因为当我滚动文本窗口时滚动不会发生.我观察到的唯一方法是拖动滚动条.

    scrollbar = Tkinter.Scrollbar(group4.interior())
    scrollbar.pack(side = 'right',fill='y')

    Details1 = Output()        
    outputwindow = Tkinter.Text(group4.interior(), yscrollcommand = scrollbar.set,wrap = "word",width = 200,font = "{Times new Roman} 9")
    outputwindow.pack( side = 'left',fill='y')
    scrollbar.config( command = outputwindow.yview )
    outputwindow.yview('end')
    outputwindow.config(yscrollcommand=scrollbar.set)
    outputwindow.insert('end',Details1)
Run Code Online (Sandbox Code Playgroud)

在程序中,函数output()将连续发送应滚动的数据

提前致谢,

Bry*_*ley 19

您可以使用see方法将文本窗口小部件滚动到任何位置,该方法接受索引.

例如,要使窗口小部件的最后一行可见,您可以使用索引"end":

outputwindow.see("end")
Run Code Online (Sandbox Code Playgroud)

这是一个完整的工作示例:

import time
try:
    # python 2.x
    import Tkinter as tk
except ImportError:
    # python 3.x
    import tkinter as tk

class Example(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)

        self.text = tk.Text(self, height=6, width=40)
        self.vsb = tk.Scrollbar(self, orient="vertical", command=self.text.yview)
        self.text.configure(yscrollcommand=self.vsb.set)
        self.vsb.pack(side="right", fill="y")
        self.text.pack(side="left", fill="both", expand=True)

        self.add_timestamp()

    def add_timestamp(self):
        self.text.insert("end", time.ctime() + "\n")
        self.text.see("end")
        self.after(1000, self.add_timestamp)

if __name__ == "__main__":
    root =tk.Tk()
    frame = Example(root)
    frame.pack(fill="both", expand=True)
    root.mainloop()
Run Code Online (Sandbox Code Playgroud)


Mik*_*eyB 10

看一下Text.see(...)方法。

TextWidget.insert(tk.END, str(new_txt))
TextWidget.see(tk.END)
Run Code Online (Sandbox Code Playgroud)

我使用此模式将(又名insert)文本添加new_txt到我的输出窗口并滚动 ( see) 到底部 ( tk.END)