Programmatically close gtk window
Using destroy method doesn't work as expected, as the 'delete-event' callbacks are not called on the destroyed window, thus a editor, for example, won't have a chance to ask the user if the file has to be saved.
[3|zap@zap|~]python
Python 2.7.3 (default, Jul 24 2012, 10:05:38)
[GCC 4.7.0 20120507 (Red Hat 4.7.0-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gtk
>>> w = gtk.Window()
>>> w.show()
>>> def cb(w,e):
... print "cb", w, e
... return True
...
>>> w.connect ('delete-event', cb)
>>> w.destroy()
In the above example invoking w.destroy() won't invoke the callback, while clicking on the "close" button will invoke it (and window won't close because callback returned True).
Thus, you have to both emit the signal and then destroy the widget, if signal handlers returned False, e.g:
if not w.emit("delete-event", gtk.gdk.Event(gtk.gdk.DELETE)):
w.destroy()
You should use window.destroy()
when deleting a window in PyGTK (or for that matter any kind of widget). When you call window.destroy()
the window will emit a delete-event
event automatically.
Furthermore, when emitting a signal for an event using PyGTK, it is almost always required to also pass an event object to the emit method (see the pyGObject documentation for the emit method). When an attempt is made to pass a gtk.gdk.Event(gtk.EVENT_DELETE)
to an object's emit method for a delete-event
it will not work. E.g:
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gtk
>>> w = gtk.Window()
>>> w.show()
>>> w.emit("delete-event", gtk.gdk.Event(gtk.gdk.DELETE))
False
Perhaps the best way, though, is to simply use the del
statement which will automatically delete the window/widget and do any necessary cleanup for you. Doing this is more 'pythonic' than calling window.destroy() which will leave around a reference to a destroyed window.