It works ... but why?

The following code produces a responsive window.

import wx

app = wx.App()
frame = wx.Frame(parent=None,title="Test")
frame.Show()
app.MainLoop()

How does the app “know” that the frame belongs to it? I thought, “Maybe the app owns the menubar?” But no, this does nothing:

import wx

app = wx.App()
app.MainLoop()

What’s going on under the hood here?

Running the following code:

import wx

app = wx.App()
print("app.TopWindow =", app.TopWindow)
frame = wx.Frame(parent=None,title="Test")
print("frame =", frame)
print("app.TopWindow =", app.TopWindow)
frame.Show()
app.MainLoop()

outputs:

app.TopWindow = None
frame = <wx._core.Frame object at 0x7f7b5c6252d0>
app.TopWindow = <wx._core.Frame object at 0x7f7b5c6252d0>

I’m guessing that when the Frame is created it calls wx.GetApp() and then checks if the app has a TopWindow. Then if it doesn’t, it sets itself as the TopWindow by calling app.SetTopWindow(self) ?

1 Like

well, you can make it even shorter (and never forget there is this glorious SIP Done around wx) :joy:

import wx

app = wx.App()
wx.Frame(None, title="Test").Show()
app.MainLoop()

The library maintains a list of top-level windows. You can access it with wxGetTopLevelWindows()