tkinter thread communication

Viewed 1431

I have code that should show communication between tkinter widget (NOTE: not implemented yet) and another thread. As communication between those two I choose python queue. To see what is really happening print is shown in console and it's not what I would expect.

As can be seen in console output after sleep time in generate_text output from process is shown. What I expected is that as generate_text is slower then process I would see a lot more process is called then Item x, but this is not happening.

import tkinter as tk
import threading
import queue
import time

def generate_text(storage):
    count = 0
    while True:
        message = "Item {}".format(count)
        storage.put(message)
        print(message)

        count +=1

        time.sleep(3000/1000)

def process(storage):
    print("process is called")

    try:
        storage.get()
    except queue.Empty:
        print("queue empty")

    # register awake function
    root.after(500, process, message)

# init variables
message = queue.Queue()

root = tk.Tk()

t = threading.Thread(target=generate_text, args=(message,))
t.setDaemon(True)
t.start()

root.after(500, process, message)
root.mainloop()

Output:

Item 0
process is called
process is called
Item 1
process is called
Item 2
process is called
Item 3
process is called...

Desired output:
Item 0
process is called
process is called
process is called
process is called
process is called
process is called
Item 1
2 Answers
Related