简体   繁体   中英

How can I exit out of a wxPython application cleanly?

The package wxPython is very good for developing GUI-interface applications in Python, but so far, the only methods that I have found to exit from an application developed in wxPython launched from the Python command line always generate a runtime error when the application is closed programmatically. For example, the method Frame.Destroy() generates the error:

Runtime error 
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\PythonSamples\ArcGIS Examples\TIGER Data Loader.py", line 522, in 
<module>
    frame.Destroy()
RuntimeError: wrapped C/C++ object of type Frame has been deleted

A similar error message is generated if Frame.Close() is called. The only way that I have found to close an application window generated by wxPython WITHOUT generating a run-time error is by deleting the wx.App object:

app=wx.App()
frame = wx.Frame(etc....)
.
.
.

and somewhere in the program where you want to exit the Frame window, you issue

del app

This seems like a bad way to terminate an application. Is there a better way that does NOT generate a run-time error message?

calling frame.Destroy() in an event deletes the frame, but the program then returns to the wx mainloop.

When the mainloop finds that the frame has been destroyed, the error occurs.

Instead (like when using threads), use wx.CallAfter so wx it is executed in the main thread and somewhere where wx expects such changes. For you:

wx.CallAfter(frame.Destroy)

note as suggested in comments that it's cleaner to do:

wx.CallAfter(frame.Close)

because it gives your app a chance to call some cleanup code, unlike Destroy

How about frame.Close() ? Docs are here

For reference, the following code doesn't spit out any error on my machine:

import wx

class MyFrame(wx.Frame):

    def __init__(self):
        super().__init__(None, title="Close Me")
        panel = wx.Panel(self)

        closeBtn = wx.Button(panel, label="Close")
        closeBtn.Bind(wx.EVT_BUTTON, self.onClose)

    def onClose(self, event):
        self.Close()

if __name__ == "__main__":
    app = wx.App(False)
    frame = MyFrame()
    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