Python 3.x 在PyGTK中,如何启动线程并仅在线程终止时继续调用函数
在阅读了许多关于线程和.join函数的问题后,我仍然找不到如何调整basic,使其与我的用例相匹配:Python 3.x 在PyGTK中,如何启动线程并仅在线程终止时继续调用函数,python-3.x,multithreading,pygtk,pygobject,Python 3.x,Multithreading,Pygtk,Pygobject,在阅读了许多关于线程和.join函数的问题后,我仍然找不到如何调整basic,使其与我的用例相匹配: #!/bin/python3 import threading import time from gi.repository import GLib, Gtk, GObject def app_main(): win = Gtk.Window(default_height=50, default_width=300) win.connect("destroy", Gtk.ma
#!/bin/python3
import threading
import time
from gi.repository import GLib, Gtk, GObject
def app_main():
win = Gtk.Window(default_height=50, default_width=300)
win.connect("destroy", Gtk.main_quit)
def update_progess(i):
progress.pulse()
progress.set_text(str(i))
return False
def example_target():
for i in range(50):
GLib.idle_add(update_progess, i)
time.sleep(0.2)
def start_actions(self):
print("do a few thing before thread starts")
thread = threading.Thread(target=example_target)
thread.daemon = True
thread.start()
print("do other things after thread finished")
mainBox = Gtk.Box(spacing=20, orientation="vertical")
win.add(mainBox)
btn = Gtk.Button(label="start actions")
btn.connect("clicked", start_actions)
mainBox.pack_start(btn, False, False, 0)
progress = Gtk.ProgressBar(show_text=True)
mainBox.pack_start(progress, False, False, 0)
win.show_all()
if __name__ == "__main__":
app_main()
Gtk.main()
如何使此代码打印在线程结束后执行其他操作只有在我的线程终止并且不冻结主窗口后才能执行?首先,要明确的是,调用其start方法后,线程还没有完成 查看线程中运行的代码的定义:
def example_target():
for i in range(50):
GLib.idle_add(update_progess, i)
time.sleep(0.2)
这基本上是重复以下50次:
告诉GTK在下一次系统空闲时执行update_progress,因为没有要处理的事件。
睡眠0.2秒。
您可以在线程结束后定义函数,并在线程结束时安排该函数:
def example_target():
for i in range(50):
GLib.idle_add(update_progess, i)
time.sleep(0.2)
# loop is finished, thread will end.
GLib.idle_add(after_thread)
谢谢运行GLib.idle\u addafter\u线程正是我所需要的。很好的提示,谢谢!