我正在构建一个Tkinter GUI,我有一个需要一段时间才能完成的过程,所以我对它进行了线程化处理,以防止GUI挂起。让我们调用线程化函数foo。一旦foo完成,我需要调用另一个函数bar。需要从主线程调用bar (它使用的matplotlib方法在线程内部不起作用)。
我似乎不能完全理解我该怎么做。我想加入线程,但这只会导致GUI挂起。我还想过使用一个信号变量,我会在foo的最后一行更改它,以告诉我的程序的其余部分它已经完成,是时候执行bar了,但是我不知道如何在不挂起图形用户界面的情况下在主线程中连续检查这个变量。有什么想法吗?
使用Python 3.7
发布于 2020-09-24 09:13:31
您可以使用threading.Event()对象通知主线程,并使用after()定期调用函数来检查Event()对象,以确定何时调用bar()。
下面是一个简单的例子:
import tkinter as tk
import threading
import time
def foo(event):
print('foo started')
time.sleep(5)
print('foo done')
# notify main thread
event.set()
def bar():
print('hello')
def check_event(event, callback):
print('.', end='')
if event.is_set():
# thread task is completed
callback()
else:
# check again 100 ms (adjust this to suit your case) later
root.after(100, check_event, event, callback)
root = tk.Tk()
# create the `Event()` object
event = threading.Event()
# start the checking
check_event(event, bar)
# start the thread task
threading.Thread(target=foo, args=(event,)).start()
root.mainloop()https://stackoverflow.com/questions/64037017
复制相似问题