In my learning python process, I came across the typical freezing problem when main thread is blocked by a long running function. The solution I found was basically starting a new thread. I ended up having 2 ways that seemed to be working correctly, but I would love to know if my understanding is correct.
The first way I believe the pb.destory() is an example of updating UI from a non-main thread
# --- functions ---
def longFunction():
for i in range(10):
print(i)
time.sleep(0.25)
# I believe this is updating the UI from the non-main thread (remove the progress bar)
pb.destroy()
def createNewThread():
# I am expecting the prgoressbar animation to not get blocked/freeze.
pb.start(10)
pb.pack()
thread = threading.Thread(target=longFunction)
thread.daemon = True
thread.start()
root = tk.Tk()
pb = Progressbar(root,mode='indeterminate')
tk.Button(root,text='START', command=createNewThread).pack()
root.mainloop()
The second way, I basically tried to use after() with a flag that I checks on periodically. I believe in this one the UI update happens in the main thread
# --- functions ---
def longFunction():
for i in range(10):
print(i)
time.sleep(0.25)
global isDone
isDone = True
# Check on isDone flag every 100 ms
def checkFlag():
global isDone
if isDone:
# I believe this is updating the UI from the main thread (remove the progress bar)
pb.destroy()
else:
root.after(100,checkFlag)
def createNewThread():
# I am expecting the prgoressbar animation to not get blocked/freeze.
pb.start(10)
pb.pack()
thread = threading.Thread(target=longFunction)
thread.daemon = True
thread.start()
root.after(100,checkFlag)
# flag
isDone = False
root = tk.Tk()
pb = Progressbar(root,mode='indeterminate')
tk.Button(root,text='START', command=createNewThread).pack()
root.mainloop()
My questions are:
1- Are my assumptions correct where the first way is updating the UI from non-main thread and the 2nd way is updating the UI from the main thread?
2- Is there an issue in updating the UI from a non-main thread ( I know in WPF/C# it causes too many problems)
3- Is there a better solution?