我试图在用户尝试退出我的应用程序时要求其确认。但是我不知道如何捕捉用户退出应用程序的所有不同方式:窗口上有“ X”按钮Alt + F4,我本人在i3上使用Alt + Shift + Q。
一个人怎么会这样呢?
您应该连接到delete-event
的Gtk.Window
您使用的应用程序窗口。使用delete-event
,您可以显示一个确认对话框,并且可以根据用户的响应来返回True
-表示您已处理该事件,并且应停止信号传播。或False
return-表示信号传播应继续,这将导致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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句