Search code examples
wxpython

What bind to use to detect FlatNotebook tab page closing vis FNB_X_ON_TAB


I'm using wxPython FlatNotebook widget and have enabled the FNB_X_ON_TAB style. But what bind event triggers on this action (clicking the x in the tab to close it)?

import wx
import wx.lib.agw.flatnotebook as fnb


class MyFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, -1, "FlatNotebook Demo")
        panel = wx.Panel(self)
        notebook = fnb.FlatNotebook(panel, -1)
        self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CLOSED, self.popup_close_tab, id=100)
        for i in range(3):
            caption = "Page %d" % (i + 1)
            notebook.AddPage(self.CreatePage(notebook, caption), caption)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(notebook, 1, wx.ALL | wx.EXPAND, 5)
        panel.SetSizer(sizer)
    
    def CreatePage(self, notebook, caption):
        '''
        Creates a simple :class:`Panel` containing a :class:`TextCtrl`.
        :param `notebook`: an instance of `FlatNotebook`;
        :param `caption`: a simple label.
        '''
        p = wx.Panel(notebook)
        wx.StaticText(p, -1, caption, (20, 20))
        wx.TextCtrl(p, -1, "", (20, 40), (150, -1))
        return p

    def popup_close_tab(self, event):
        print("popup_close_tab")
        #self.close_tab()

# our normal wxApp-derived class, as usual
app = wx.App(0)
frame = MyFrame(None)
app.SetTopWindow(frame)
frame.Show()
app.MainLoop()

Solution

  • You are forcing the widget Id in the Bind command, to be 100.
    But nothing has been set to an Id of 100.
    You have options:

    • Set the notebooks Id to 100
    • Leave the Id out of the Bind, assuming you have only 1 FlatNotebook
    • Get the Id in the Bind
    • Bind to the widget not self

    So:

    • notebook = fnb.FlatNotebook(panel, 100)
    • self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CLOSED, self.popup_close_tab)
    • self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CLOSED, self.popup_close_tab, id=notebook.GetId())
    • notebook.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CLOSED, self.popup_close_tab)

    It's a pretty flexible system, however serendipity had left the building, when you made one of the few choices, that wouldn't work. :)