简体   繁体   中英

How do I detect closing wxPython?

I am using wxpython...How can I detect and perform a function if someone clicks the Red 'X' on the top right corner ( Close button )? What is the code? Can someone please help me? Thanks!

You are looking for EVT_CLOSE .

eg

import wx

class Test(wx.Frame):

    def __init__(self,parent):
        wx.Frame.__init__(self,parent,title="Main Window",size = (300,200))
        panel = wx.Panel(self)
        menubar=wx.MenuBar()
        firstm=wx.Menu()

        fm1 = wx.MenuItem(firstm, -1, 'Quit\tAlt+Q')
        firstm.Append(fm1)
        self.Bind(wx.EVT_MENU, self.OnExit, id=fm1.GetId())

        # Catch Clicking on the Corner X to close
        self.Bind(wx.EVT_CLOSE, self.OnExit)

        menubar.Append(firstm,"File")

        self.SetMenuBar(menubar)

        t = wx.StaticText(panel,-1,"Testing 1 2 3 ....", pos=(10,20))

    def OnExit(self, event):
        # To discover how you got here,
        # you can either test the event type or define a separate function for EVT_CLOSE,
        # most of the time you don't care
        if event.GetEventType() == wx.EVT_CLOSE.typeId:
            print("Close using X")
        else:
            print("Close using Menu or Alt+Q")
        self.Destroy()
                
if __name__=='__main__':
    app=wx.App()
    frame=Test(None)
    frame.Show()
    app.MainLoop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM