Search code examples
pythonpython-2.7eventswxpython

How do I stop a windows from closing after I raise wx.EVT_CLOSE in wxPython?


I have a Frame and once the user clicks on the exit button, I want a dialogue box to open and ask him if he really wants to close the window.

So I did:

self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

and then I have the Callback:

def OnCloseWindow(self, event):
    dialog = wx.MessageDialog(self, message = "Are you sure you want to quit?", caption = "Caption", style = wx.YES_NO, pos = wx.DefaultPosition)
    response = dialog.ShowModal()

    if (response == wx.ID_YES):
        Pairs = []
        self.list_ctrl_1.DeleteAllItems()
        self.index = 0
        self.Destroy()
    elif (response == wx.ID_NO):
        wx.CloseEvent.Veto(True)
    event.Skip()

This works, However, I get the error:

TypeError: unbound method Veto() must be called with CloseEvent instance as first argument (got bool instance instead)

How do I catch the closeWindows instance of the event that is raised?


Solution

  • You do not really need to do that much. If you catch the event and do not call event.Skip(), it does not get propagated forward. So if you catch the event and do not call event.Skip() or self.Destroy(), the window stays open.

    import wx
    
    class MainWindow(wx.Frame):
        def __init__(self, *args, **kwargs):
            wx.Frame.__init__(self, *args, **kwargs)
            self.panel = wx.Panel(self)
            self.Bind(wx.EVT_CLOSE, self.on_close)
            self.Show()
    
        def on_close(self, event):
            dialog = wx.MessageDialog(self, "Are you sure you want to quit?", "Caption", wx.YES_NO)
            response = dialog.ShowModal()
            if response == wx.ID_YES:
                self.Destroy()
    
    app = wx.App(False)
    win = MainWindow(None)
    app.MainLoop()