Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threading in Gtk python

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 file

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

app=Gui()
Gtk.main()

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() runs the main thread.

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

Is my thinking correct or have I missed something?

EDIT: Ok,
on_update_click function:

            Thread(target=update).start(). 

K, computer does not freeze anymore :D

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.

like image 231
zeref Avatar asked Sep 07 '25 01:09

zeref


1 Answers

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()

At first I used:

thread.start_new_thread(update())

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.

I then just added:

Thread(target=update).start()

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

by adding: GObject.threads_init()

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

like image 174
zeref Avatar answered Sep 09 '25 04:09

zeref