当用户试图退出我的应用程序时,我试图询问用户是否确认。但我不知道如何捕捉用户退出应用程序的所有不同方式:窗口上有“X”按钮,Alt+F4,我自己在 i3 上使用 Alt+Shift+Q。
人们会怎么做呢?
请您参考如下方法:
您应该连接到您在应用程序窗口中使用的Gtk.Window 的delete-event。 delete-event 允许您显示一个确认对话框,并且根据用户响应,您可以返回 True — 这意味着您处理了该事件,并且应停止信号传播;或返回 False — 意味着信号传播应该继续,这将导致在小部件上调用 destroy() 方法。
delete-event 信号是响应窗口管理器的终止请求而发出的;例如,使用窗口菜单时;像 Alt+F4 这样的组合键;或窗口的“关闭”按钮。
一个简单的例子来证明上面的内容:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gio
from gi.repository import Gtk
class AppWindow (Gtk.ApplicationWindow):
def __init__(self):
Gtk.ApplicationWindow.__init__(self)
self.set_default_size(200, 200)
# Override the default handler for the delete-event signal
def do_delete_event(self, event):
# Show our message dialog
d = Gtk.MessageDialog(transient_for=self,
modal=True,
buttons=Gtk.ButtonsType.OK_CANCEL)
d.props.text = 'Are you sure you want to quit?'
response = d.run()
d.destroy()
# We only terminate when the user presses the OK button
if response == Gtk.ResponseType.OK:
print('Terminating...')
return False
# Otherwise we keep the application open
return True
def on_activate(app):
# Show the application window
win = AppWindow()
win.props.application = app
win.show()
if __name__ == '__main__':
# Create an application instance
app = Gtk.Application(application_id='com.example.ExampleApp', flags=0)
# Use ::activate to show our application window
app.connect('activate', on_activate)
app.run()
