所以我正忙着编写一个应用程序,需要在一定时间后检查网站的更新,我正在使用 python 和 Gtk +3
main.py 文件
class Gui:
...
def on_update_click():
update()
app=Gui()
Gtk.main()
更新.py文件
def update():
#check site for updates
time.sleep(21600) #check again in 6hrs
我怀疑我必须使用线程。 我的想法是:
Gtk.main() 运行主线程。
当用户点击更新按钮时,update() 在后台运行。 #线程 2
我的想法正确还是我错过了什么?
编辑:
好的,
on_update_click 函数:
Thread(target=update).start().
K,电脑不再死机了:D
所以现在发生的是,只有当我关闭 Gtk.main() 时,更新线程才会启动。关闭 UI 时继续更新很好,但我也希望它在 UI 启动时启动。
最佳答案
所以我终于设法让它工作了。 我需要说:
from gi.repository import Gtk,GObject
GObject.threads_init()
Class Gui:
.....
......
def on_update_click():
Thread(target=update).start()
起初我使用:
thread.start_new_thread(update())
在 on_update_click 函数中。正如我的 J.F Sebastian 所提到的,这是不正确的,因为这会立即调用该线程。这卡住了我的整个计算机。
然后我刚刚添加:
Thread(target=update).start()
on_update_clicked 函数仅在主线程 Gtk.main() 关闭后才起作用。所以线程没有同时运行。
通过添加: GObject.threads_init()
这允许线程串行运行到 python 解释器: Threads in Gtk !
关于python - Gtk python 中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11923008/