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?
after()
is simply tkinter's way of managing events to be run after a specific time. It is no different than just calling the function/command directly but simply done at a later time. I do not believe it has any interaction with the threaded task it is calling. I don't work with the global namespace from within a thread like this though so I am not sure. I typically pass anything that needs to be updated to the thread and then make changes from there. – CaparisonTrue
then "Is root.after thread-safe?" can't beTrue
? – Burhansafter
simply adds something to a queue, it doesn't touch the internal widget objects. – Opportunaroot
then does that mean the event is actually occurring in the main thread and has no issues from being assigned during a threaded function? – Caparisonmainloop
is running in -- which is presumably the main thread. However, if you callupdate
from some other thread, it will probably be run in that thread. – Opportunaupdate()
from another thread that sounds like it could cause some issues. – Caparison