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