Python Tkinter Text Widget with Auto & Custom Scroll

后端 未结 3 953
天涯浪人
天涯浪人 2021-02-09 15:08

I wrote a simple Tkinter based Python application that reads text from a serial connection and adds it to the window, specifically a text widged.

After a lot of tweaks a

3条回答
  •  独厮守ぢ
    2021-02-09 15:12

    It's hard to tell what's really going on but have you considered using a Queue?

    from Tkinter import *
    import time, Queue, thread
    
    def simulate_input(queue):
        for i in range(100):
            info = time.time()
            queue.put(info)
            time.sleep(0.5)
    
    class Demo:
        def __init__(self, root, dataQueue):
            self.root = root
            self.dataQueue = dataQueue
    
            self.text = Text(self.root, height=10)
            self.scroller = Scrollbar(self.root, command=self.text.yview)
            self.text.config(yscrollcommand=self.scroller.set)
            self.text.tag_config('newline', background='green')
            self.scroller.pack(side='right', fill='y')
            self.text.pack(fill='both', expand=1)
    
            self.root.after_idle(self.poll)
    
        def poll(self):
            try:
                data = self.dataQueue.get_nowait()
            except Queue.Empty:
                pass
            else:
                self.text.tag_remove('newline', '1.0', 'end')
                position = self.scroller.get()
                self.text.insert('end', '%s\n' %(data), 'newline')            
                if (position[1] == 1.0):
                    self.text.see('end')
            self.root.after(1000, self.poll)
    
    q = Queue.Queue()
    root = Tk()
    app = Demo(root, q)
    
    worker = thread.start_new_thread(simulate_input, (q,))
    root.mainloop()
    

提交回复
热议问题