gpt4 book ai didi

multithreading - tkinter 线程通信

转载 作者:行者123 更新时间:2023-12-02 08:12:15 27 4
gpt4 key购买 nike

我有代码应该显示 tkinter 小部件(注意:尚未实现)和另一个线程之间的通信。作为这两者之间的通信,我选择 python 队列。要查看真正发生的事情,控制台中会显示打印,这不是我所期望的。

正如在 generate_text 输出的 process sleep 时间后的控制台输出中可以看到的那样。我期望的是,由于 generate_textprocess 慢,我会看到更多的 process is calledItem x ,但这并没有发生。

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()

输出:

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

最佳答案

storage.get() 是一个阻塞函数。在队列中有一个项目之前,它不会到达 root.after(500, process, message) 调用。

您可以使用 storage.get_nowait()storage.get(False) 来获得所需的行为。

More about Queue

关于multithreading - tkinter 线程通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45661413/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com