Search code examples
pythonwxpythonpython-unittest

How to destroy a wxPython frame in unittest


I'm running unittests on my wxPython GUI. The tests work approximately as expected, except that the frames that I create don't go away. By the end of my tests, I have 30 or more top level windows. Here is my setUp and tearDown code:

def setUp(self):
    self.app = wx.App()
    self.frame = MyGridFrame()

def tearDown(self):
    self.frame.Destroy()
    for wind in wx.GetTopLevelWindows():
        wind.Destroy()
    self.app.Destroy()

I tried several different combinations of the four lines you see in my tearDown function, but they all have the same (lack of any) effect.


Solution

  • Here is a tearDown function that works correctly from the documentation: https://github.com/wxWidgets/Phoenix/blob/master/unittests/wtc.py

    def tearDown(self):
        def _cleanup():
            for tlw in wx.GetTopLevelWindows():
                if tlw:
                    tlw.Destroy()
            wx.WakeUpIdle()
            #self.app.ExitMainLoop()   
        wx.CallLater(50, _cleanup)
        self.app.MainLoop()
        del self.app
    

    Presumably the event loop has to be running to actually catch and process the close event generated by calling window.Destroy(). It makes sense, but took me a while to figure out.