autoscroll of text and scrollbar in python text box

后端 未结 2 1735
感情败类
感情败类 2020-12-19 01:56

I have a tkinter \'Text\' and \'Scrollbar\' working fine. In my program in the text window automatically lines will keep on adding. So When a new line of text is inserted an

相关标签:
2条回答
  • 2020-12-19 01:58

    Take a look at Text.see(...) method.

    TextWidget.insert(tk.END, str(new_txt))
    TextWidget.see(tk.END)
    

    I used this pattern to add (aka insert) text new_txt to my output window and scroll (see) to the bottom (tk.END)

    0 讨论(0)
  • 2020-12-19 02:14

    You can cause the text widget to scroll to any location with the see method, which takes an index.

    For example, to make the last line of the widget visible you can use the index "end":

    outputwindow.see("end")
    

    Here's a complete working example:

    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()
    
    0 讨论(0)
提交回复
热议问题