Reputation: 19780
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')
Upvotes: 9
Views: 20128
Reputation: 1391
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.
Upvotes: 11
Reputation: 3538
For GTK 3.10 and above.
void
gtk_window_close (GtkWindow *window);
Requests that the window is closed, similar to what happens when a window manager close button is clicked.
This function can be used with close buttons in custom titlebars.
Upvotes: 2
Reputation: 141
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()
Upvotes: 14