2

Trying to update tkinter Label based on what happens in a function that follows the thread running tkinter.

The code below (from https://stackoverflow.com/a/69743264/15409926) prints the value sent via queue from the main function, but the value that's sent does not show in the GUI.

What is shown in GUI vs Print

Please share how to update the text in GUI as seen in terminal.

Code:

import tkinter as tk
from threading import Thread
import queue
import time

class GUI(Thread):
    def __init__(self, queue):
        super().__init__()
        self.queue = queue
        self.start()

    def run(self):
        global label
        self.root = tk.Tk()

        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()

        width = int(screen_width*.12)
        height = int(screen_height)
        x = int(screen_width - width)
        y = int(screen_height*.025)

        self.root.geometry(f'{width}x{height}+{x}+{y}')

        label = tk.Label(self.root, text= self.queue.get())
        label.pack()

        # run first time after 100ms (0.1 second)
        self.root.after(50, self.check_queue)

        self.root.mainloop()

    def check_queue(self):
        #if not self.queue.empty():
        while not self.queue.empty():
            text = self.queue.get()
            label.configure(text=text)
            print(text)
        self.root.after(50, self.check_queue)
        # run again after 100ms (0.1 second)

q = queue.Queue()
gui = GUI(q)

def main():
    for j in range(100):
        q.put(f'Iteration:{j}')
        time.sleep(1)

if __name__ == '__main__':
    main()
555
  • 35
  • 4

0 Answers0