Programmatically close the GTK window

If you have a GTK subwindow and want to close it programmatically (for example, by pressing the save button or the exit key), is there a preferred way to close the window?

EG,

window.destroy() # versus window.emit('delete-event') 
+8
source share
3 answers

You must use window.destroy() when deleting a window in PyGTK (or, for that matter, any widget). When you call window.destroy() , the window automatically raises the delete-event .

In addition, when emitting a signal for an event using PyGTK, it is almost always required to also pass the event object to the emit method (see the pyGObject documentation for the emit method ). When an attempt is made to pass the gtk.gdk.Event(gtk.EVENT_DELETE) method to the method of emitting an object for delete-event , it will not work. For example:

 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 is to simply use the del operator, which will automatically remove the window / widget and do the necessary cleanup for you. Doing this is more "pythonic" than calling window.destroy (), which will leave around the link to the damaged window.

+9
source

Using the destroy method does not work properly, since the delete-event callbacks are not called in the destroyed window, so the editor, for example, will not be able to ask the user if there is a file to save.

 [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, calling w.destroy () will not cause a callback, and when you click the close button, it is called (and the window will not close because the callback returns True).

Thus, you must both emit a signal and then destroy the widget if the signal handlers return False, for example:

 if not w.emit("delete-event", gtk.gdk.Event(gtk.gdk.DELETE)): w.destroy() 
+15
source

For GTK 3.10 and higher.

 void gtk_window_close (GtkWindow *window); 

Requests that the window be closed, similar to what happens when the close button of the window manager is pressed.

This function can be used with the close buttons in custom headers.

gtk_window_close ()

0
source

All Articles