以编程方式关闭 gtk 窗口
如果 GTK 中有一个子窗口,并且您想以编程方式关闭它(例如,按保存按钮或退出键),是否有关闭窗口的首选方法?
例如,
window.destroy()
# versus
window.emit('delete-event')
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')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 destroy 方法无法按预期工作,因为不会在被销毁的窗口上调用“删除事件”回调,因此编辑器将没有机会询问用户是否必须保存文件。
在上面的示例中,调用 w.destroy() 不会调用回调,而单击“关闭”按钮将调用它(并且窗口不会关闭,因为回调返回 True)。
因此,如果信号处理程序返回 False,则必须发出信号,然后销毁小部件,例如:
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.
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:
在 PyGTK 中删除窗口(或任何类型的小部件)时,您应该使用 window.destroy() 。当您调用
window.destroy()
时,窗口将自动发出delete-event
事件。此外,当使用 PyGTK 为事件发出信号时,几乎总是需要将事件对象传递给发出方法(请参阅 emit 方法的 pyGObject 文档)。当尝试将
gtk.gdk.Event(gtk.EVENT_DELETE)
传递给对象的delete-event
发出方法时,它将不起作用。例如:也许最好的方法是简单地使用
del
语句,它将自动删除窗口/小部件并为您进行任何必要的清理。这样做比调用 window.destroy() 更“Pythonic”,后者会留下对已销毁窗口的引用。You should use
window.destroy()
when deleting a window in PyGTK (or for that matter any kind of widget). When you callwindow.destroy()
the window will emit adelete-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 adelete-event
it will not work. E.g: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 callingwindow.destroy()
which will leave around a reference to a destroyed window.适用于 GTK 3.10 及以上版本。
gtk_window_close ()
For GTK 3.10 and above.
gtk_window_close ()