Antimony
Antimony

Reputation: 2240

Exit from infinite loop after gtk window closes

I'm creating a program that keeps checking for change in a MySQL database, and according updates a GTK display. The part that keeps checking is in an infinite loop.

What I want is that once the GTK window has been closed, I can break out of the infinite loop.

But I don't know what condition to use for that. I've tried

if !window:

and

if window == None:

but in either case, it doesn't work.

The structure of my code is like this:

while True:

    # my code

    while gtk.events_pending():
         gtk.main_iteration()

    # something to exit here

window.connect("destroy", gtk.main_quit())

I don't know if placing "window.connect" there can cause a problem, because the window seems to close just fine. Also, if I placed it within the loop, or before the loop, I'd get a Runtime Error: called outside of mainloop.

So to re-iterate, how do I exit the infinite loop using the closure of the window as a condition? I don't want the user to have to use Ctrl + C.

Thanks in advance!

Upvotes: 1

Views: 2801

Answers (2)

unutbu
unutbu

Reputation: 879083

The basic structure of a pygtk app is usually something like this:

win = gtk.MyWindow()
win.connect("destroy", gtk.main_quit)  # Note no paretheses after main_quit. 
gobject.timeout_add(1000, win.check_DB)  
win.show_all()
gtk.main()

The gobject.timeout_add command will call the win.check_DB method every 1000 milliseconds.


In win.connect("destroy", gtk.main_quit) it is important not to put parentheses after main_quit. You are passing the function object gtk.main_quit to the win.connect method, not the return value of having called gtk.main_quit(), which is what would happen if you add the parentheses.

Since gtk.main_quit() quits the app, using parentheses here halts the program too early.

Upvotes: 0

anttix
anttix

Reputation: 7779

This is a classical background thread problem. You need to have a loop like this:

closing = False

while not closing:
    // do the MySQL stuff

And then connect a signal handler to window destroy event that sets closing to True

Upvotes: 1

Related Questions