tkinter的`after`方法是线程安全的吗?

时间:2019-09-26 14:11:45

标签: python multithreading tkinter thread-safety

由于tkinter不是线程安全的,因此我经常看到人们使用Active方法将一些代码排队以便在主线程中执行。这是一个示例:

after

因此,与其直接在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() 线程中执行root.title('foo'),不如将它与worker放入队列,然后让主线程执行它。但是,调用root.after是否不如调用root.after一样糟糕? root.title是线程安全的吗?

1 个答案:

答案 0 :(得分:0)

after是线程安全的,因为它是根据call来实现的,如果CPython和Tcl是在线程支持下构建的,则{p} source code通常根据CPython standard min-cut problem on graphs是线程安全的。最常见的情况)。这意味着相当大的tkinter方法是线程安全的,但不是全部(特别是eval)。

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