Search code examples
gtkpygtk

Programmatically close gtk window


If you have a sub-window in GTK and you want to close it programmatically (e.g., pressing a save button or the escape key), is there a preferred way to close the window?

E.g.,

window.destroy()
# versus
window.emit('delete-event')

Solution

  • 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.