Gtk python中的线程 [英] Threading in Gtk python

查看:105
本文介绍了Gtk python中的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正忙于编写需要在一定时间后从网站检查更新的应用程序,我正在将python与Gtk +3一起使用

So I'm busy writing an application that needs to check for updates from a website after a certain amount ouf time, I'm using python with Gtk +3

main.py文件

class Gui:
    ...
    def on_update_click():
        update()

app=Gui()
Gtk.main()

update.py文件

update.py file

def update():
    #check site for updates
    time.sleep(21600) #check again in 6hrs

我怀疑我必须使用线程. 我的想法是:

I suspect I'll have to use threading. my thinking is:

Gtk.main()运行主线程.

Gtk.main() runs the main thread.

当用户单击更新按钮时,update()在后台运行. #thread 2

when the user clicks the update button, update() runs in the background. #thread 2

我的想法正确吗?或者我错过了什么?

Is my thinking correct or have I missed something?

好,
on_update_click函数:

Ok,
on_update_click function:

            Thread(target=update).start(). 

K,计算机不再冻结:D

K, computer does not freeze anymore :D

所以现在发生的是,只有当我关闭Gtk.main()时,更新线程才会启动.很好的是,当用户界面关闭时可以继续更新,但是我也希望它在用户界面启动时开始.

so what happens now is that only when I close Gtk.main() does the update thread only start. It's good that is continues to update when the UI is closed, but i'd also like it to start when the UI is up.

推荐答案

所以我终于设法使它开始工作. 我需要说:

So I finally managed to get it to work. I needed to say:

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所提到的,这是不正确的,因为这将立即调用此线程.这冻结了我的整个计算机.

in the on_update_click function. As mentioned my J.F Sebastian this was incorrect as this would immediately call this thread. This froze my whole computer.

然后我才添加:

Thread(target=update).start()

on_update_clicked函数仅在关闭主线程Gtk.main()后才起作用.因此线程不能同时运行.

The on_update_clicked function only worked once the main Thread Gtk.main() was closed. So the threads were not running simultaneously.

通过添加: GObject.threads_init()

by adding: GObject.threads_init()

这允许线程以串行方式运行到python解释器: Gtk中的线程

this allowed for the threads to run serially to the python interpreter: Threads in Gtk!

这篇关于Gtk python中的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆