Verify Exit Dialog (wxPython)

bumsfeld 0 Tallied Votes 701 Views Share

Code snippet to show you how to verify exit events from wxPython using dialog window. One event is from menu exit and the other from frame exit (x symbol in corner).

# wxPython Frame with menubar, statusbar, and verify exit dialog
# tested with Python24 and wxPython26   by  HAB

import wx

ID_EXIT  = 102  # needed for menu

class MyFrame(wx.Frame):
    """make a frame, with menu, statusbar and exit-dialog, inherits wx.Frame"""
    def __init__(self):
        # create a frame/window, no parent, default to wxID_ANY
        wx.Frame.__init__(self, None, wx.ID_ANY, 'wxPython', pos=(300, 150), size=(300, 350))
        
        # create statusbar (bottom)
        self.CreateStatusBar()
        self.SetStatusText("This is the statusbar")
        
        menu = wx.Menu()
        # "Quit this program" shows in statusbar
        menu.Append(ID_EXIT, "Exit", "Quit this program")
        
        # create menubar (top)
        menuBar = wx.MenuBar()
        menuBar.Append(menu, "File")  # usual title
        self.SetMenuBar(menuBar)

        # bind menu exit
        self.Bind(wx.EVT_MENU, self.onMenuExit, id=ID_EXIT)
        # responds to exit symbol x on frame title bar
        self.Bind(wx.EVT_CLOSE, self.onCloseWindow)

        # show frame
        self.Show(True)
        
    def onMenuExit(self, event):
        # via wx.EVT_CLOSE event, also triggers exit dialog
        self.Close(True)

    def onCloseWindow(self, event):
        # dialog to verify exit (including menuExit)
        dlg = wx.MessageDialog(self, "Want to exit?", "Exit", wx.YES_NO | wx.ICON_QUESTION)
        if dlg.ShowModal() == wx.ID_YES:
            self.Destroy()  # frame
        dlg.Destroy()

application = wx.PySimpleApp()
# create instance of class MyFrame
window = MyFrame()
# start event loop
application.MainLoop()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.