tkinter 的 `after` 方法线程安全吗? [英] Is tkinter's `after` method thread-safe?

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

问题描述

由于 tkinter 不是线程安全的,我经常看到人们使用 after 方法将一些代码排队以在主线程中执行.举个例子:

Since tkinter isn't thread-safe, I often see people use the after method to queue some code for execution in the main thread. Here's an example:

import tkinter as tk
from threading import Thread

def change_title():
    root.after(0, root.title, 'foo')

root = tk.Tk()
Thread(name='worker', target=change_title).start()
root.mainloop()

因此,我们不是在 worker 线程中直接执行 root.title('foo'),而是将其与 root.after 一起排队,然后让主线程执行它.但是调用 root.after 是不是和调用 root.title 一样糟糕?root.after 线程安全吗?

So instead of executing root.title('foo') directly in the worker thread, we queue it with root.after and let the main thread execute it. But isn't calling root.after just as bad as calling root.title? Is root.after thread-safe?

推荐答案

after 是线程安全的,因为它是根据 call 实现的,通常是线程安全的根据 CPython CPython 源代码和 Tcl 是用线程支持构建的(最常见的情况).这意味着相当大的tkinter 方法是线程安全的,但并非全部(尤其是eval).

after is thread-safe because it is implemented in terms of call which is generally thread-safe according to the CPython source code if CPython and Tcl were built with thread support (the most common case). This means quite a large footprint of tkinter methods are thread-safe, but not all (particularly eval).

如果您从某个其他 CPython 线程调用 after(或 call),它实际上会向主线程(使用 Tcl 解释器)发送线程安全消息实际与 Tcl API 交互并在主线程中运行命令.

If you call after (or call) from some other CPython thread, it will actually send a thread-safe message to the main thread (with the Tcl interpreter) to actually interact with the Tcl API and run the command in the main thread.

这篇关于tkinter 的 `after` 方法线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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