pythonwxpythonwxwidgetswxnotebook

wxpython notebook - creating new pages


I'm new here and I'm newbie in coding (since April, this year) so please be gentle ;-)

This is my simplified code. Each time I'm creating new page in the notebook by clicking "ClickMe" button. My question is: Is there any option to not use if/elif statement? There will be 10 pages or more, so a want to avoid typing each time similar code. Are there any way to use dynamically creating variable (self.page...)?

import wx

class PageOne(wx.Panel):

    def __init__(self, parent):

        wx.Panel.__init__(self, parent)
        wx.StaticText(self, -1, pos = (10,10), label = "Test")


class PageTwo(wx.Panel):

    def __init__(self, parent):

        wx.Panel.__init__(self, parent)
        wx.StaticText(self, -1, pos = (10,10), label = "Test 2")
        self.text = wx.TextCtrl(self,-1, pos = (100,10))

    def OnLoad(self, text):
        self.text.AppendText(str(text))

class MainFrame(wx.Frame):

    def __init__(self, parent, id, title, pos, size):

        wx.Frame.__init__(self, parent, id, title, pos, size)

        panel = wx.Panel(self)

        self.nb = wx.Notebook(panel)
        self.page1 = PageOne(self.nb)
        self.nb.AddPage(self.page1, "PAGE 1")

        self.button = wx.Button(self.page1, -1, pos = (100,10), label = "ClickMe")

        self.Bind(wx.EVT_BUTTON, self.OnClick, self.button)

        sizer = wx.BoxSizer()
        sizer.Add(self.nb, 1, wx.EXPAND)
        panel.SetSizer(sizer)


    def OnClick(self, event):

        page_number = self.nb.GetPageCount()

        if page_number == 1: 
            self.page2 = PageTwo(self.nb)
            self.nb.AddPage(self.page2, "PAGE 2")
            self.page2.OnLoad("PAGE 2")
        elif page_number == 2: 
            self.page3 = PageTwo(self.nb)
            self.nb.AddPage(self.page3, "PAGE 3")
            self.page3.OnLoad("PAGE 3")
        elif page_number == 3: 
            self.page4 = PageTwo(self.nb)
            self.nb.AddPage(self.page4, "PAGE 4")
            self.page4.OnLoad("PAGE 4")

class App(wx.App):

    def OnInit(self):

        self.frame = MainFrame(None, -1, "Notebook", (250,50), (500,500))
        self.frame.Show()
        return True

app = App(False)
app.MainLoop()

I found here many useful informations and I hope that someone will help me with this issue or show me the right way (if I'm making some stupid mistake/assumption).


Solution

  • I would put all the pages in a list instead of having them as separate attributes.

    def __init__(self, parent, id, title, pos, size):
        #...
        self.pages = [PageOne(self.nb)]
        #...
    
    def OnClick(self, event):
        page = self.nb.GetPageCount() + 1
        # Or: page = len(self.pages) + 1
    
        self.pages.append(PageTwo(self.nb))
        self.nb.AddPage(self.pages[page], "PAGE %d" % page)
        self.pages[page].OnLoad("PAGE %d" % page)