Is tkinter's `after` method thread-safe?

让人想犯罪 __ 提交于 2020-06-27 20:04:28

问题


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

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?


回答1:


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

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.



来源:https://stackoverflow.com/questions/58118723/is-tkinters-after-method-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!