3
votes

I’m using wxPython to write an app that will run under OS X, Windows, and Linux. I’m trying to implement the standard “Close Window” menu item, but I’m not sure how to find out which window is frontmost. WX has a GetActiveWindow function, but apparently this only works under Windows and GTK. Is there a built-in way to do this on OS X? (And if not, why not?)

2
Isn't it the case that the window that has the menu is the only window that can be receiving the close window menu event that you are processing? IE in order to activate "close window" the user already had to bring this window to the front, so ... this is the one you have to close? - GreenAsJade
@GreenAsJade I don’t think that’s correct. When I open a window as a child of the main window (the one with the menu bar), the menu bar is still visible on screen and accessible with keyboard shortcuts. - bdesham
But in any case, if they operate "close window" option of a menu on a window, then they are chosing to close that window. It would strike me as strange to operate a menu item called "close window" to close some other window. That doesn't sound to me like "standard Close Window" behaviour. - GreenAsJade
@GreenAsJade I’m talking about OS X, where there’s only one menu bar per application. (You can show different menu bars for different windows, but in my case I’m choosing not to.) Therefore there is one “Close Window” menu item, and choosing it should close whichever window is frontmost. - bdesham
Got it - let me think about that :) It needs thought because the window that is foremost is up to the window manager (OSX in this case). I'm not even sure yet why I haven't had this problem myself :) - GreenAsJade

2 Answers

1
votes

What about having a Close/Exit app menu item and use: http://wxpython.org/Phoenix/docs/html/PyApp.html?highlight=gettopwindow#PyApp.GetTopWindow

to call its Close method.

Werner

1
votes

Add close window but only for mac.

        from sys import platform

        if platform == "darwin":
            self.file_menu.Append(wx.ID_CLOSE, _("&Close Window\tCtrl-W"), "")

Bind that.

self.Bind(wx.EVT_MENU, self.on_click_close, id=wx.ID_CLOSE)

This is what I ended up using for a bigger mac relevant routine. It needs to find the focused window. That is within the top level parent. But, this command is triggered on the menubar acceleration_table so we call the close only really in mac. I don't close the main window with the control+w

    def on_click_close(self, event=None):
        try:
            window = app.GetTopWindow().FindFocus().GetTopLevelParent()
            if window is self:
                return
            window.Close(False)
        except RuntimeError:
            pass

Basically the whatever has focus and the top level parent of that thing is the window in the foreground. So go ahead and close that unless that window is the main window.