tkinter 线程通信 [英] tkinter thread communication

查看:61
本文介绍了tkinter 线程通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

正如在显示 processgenerate_text 输出中的睡眠时间后控制台输出中所见.我期望的是,由于 generate_textprocess 慢,我会看到更多 process 被调用 然后 Item x>,但这并没有发生.

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

输出:

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() is a blocking function. it won't reach the root.after(500, process, message) call until there's an item in the queue.

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

You could use storage.get_nowait() or storage.get(False) to get the desired behavior.

更多关于队列

这篇关于tkinter 线程通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆