2016-04-28 48 views

回答

3

您應該連接到您在應用程序窗口中使用的Gtk.Windowdelete-eventdelete-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() 
+0

感謝這麼詳細的解答!將嘗試實現這一點。 – joaquinlpereyra

+0

當你的主類是'class App(Gtk.Application)'類型時,你如何做到這一點? – Redsandro