问题
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