Search code examples
gtkpygtkgtk2

how to get around blocking behavior of gtk event loop in python


I've reduced my problem down to this simple example script:

#! /usr/bin/python

import hello
from threading import Thread

def myfunc():

        hello.HelloWorld().main()

t = Thread(target=myfunc)
t.start()

print '\nstill running ???'

The problem is I'm trying to find someway to get around the blocking behavior of the gtk event loop. Is this possible? As you can see, even if I call the class from a separate thread the event loop blocks further progress in the main script ("still running ???" is not printed until the gtk application is closed)


Solution

  • You should read the threading best practice for pyGTK. GTK should be used in the main thread, but still, I agree that is strange.

    I've tried the following code:

    #! /usr/bin/python
    
    import gtk
    from time import sleep
    from threading import Thread
    
    
    def myfunc():
        w = gtk.Window()
        l = gtk.Label()
        w.add(l)
        w.show_all()
        w.connect("destroy", lambda _: gtk.main_quit())
        gtk.main()
    
    def myfunc2():
        sleep (3)
    
    t = Thread(target=myfunc)
    #t = Thread(target=myfunc2)
    t.start()
    
    print '\nstill running ???'
    

    And what is worse, is that almost always the message will be printed after closing the app, but sometimes it appears before. So, there's a strange behavior here.