Search code examples
wxpythonwxnotebook

New wxNotebook-Pages stay empty in wxPython


I made some sample code to try wxNotebook, but the new inserted pages remain completely empty. If I don't use a Timer or a new Thread, but insert the pages before the MainLoop, it works. I suspect I need an Update, Refresh or something like that anywhere, but I couldn't get it to work. I use Windows 7 and Python 2.7.

import wx
import threading

class addNewPages(threading.Thread):  
    def __init__(self, nb):
        super(addNewPages, self).__init__()
        self.nb = nb
    def run(self):
        self.p = 1
        for i in range(1, 5, 1):
            threading.Timer(i, self.adp).start()
    def adp(self):
        self.newpage = Page(self.nb)
        self.newpage.SetBackgroundColour(wx.GREEN)
        wx.StaticText(self.newpage, -1, "PAGE "+str(self.p), style=wx.ALIGN_CENTRE)
        wx.CallAfter(self.nb.AddPage, self.newpage, "Page "+str(self.p))
        self.p += 1

class Page(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        wx.StaticText(self, -1, "This is a Page object", (20,20))

class MainFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title="Notebook Test")
        p = wx.Panel(self)
        self.nb = wx.Notebook(p)
        self.page1 = Page(self.nb)

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

if __name__ == "__main__":
    app = wx.App()
    mf = MainFrame()
    mf.Show()
    mf.nb.AddPage(mf.page1, "Testseite 1")
    th = addNewPages(mf.nb)
    th.start()
    app.MainLoop()

Solution

  • This appears to be a threading problem, not a notebook problem. Modifying your code as follows creates the form that you're expecting. My best guess is that this is a scope issue, but I don't know for certain.

    import wx
    
    def run(nb):
        for i in range(1, 5, 1):
            adp(nb, i)
    
    def adp(nb, p):
        newpage = Page(nb)
        newpage.SetBackgroundColour(wx.GREEN)
        wx.StaticText(newpage, -1, "PAGE "+str(p), style=wx.ALIGN_CENTRE)
        wx.CallAfter(nb.AddPage, newpage, "Page "+str(p))
    
    class Page(wx.Panel):
        def __init__(self, parent):
            wx.Panel.__init__(self, parent)
            wx.StaticText(self, -1, "This is a Page object", (20,20))
    
    class MainFrame(wx.Frame):
        def __init__(self):
            wx.Frame.__init__(self, None, title="Notebook Test")
            p = wx.Panel(self)
            self.nb = wx.Notebook(p)
            self.page1 = Page(self.nb)
    
            sizer = wx.BoxSizer()
            sizer.Add(self.nb, 1, wx.EXPAND)
            p.SetSizer(sizer)
    
    if __name__ == "__main__":
        app = wx.App()
        mf = MainFrame()
        mf.Show()
        mf.nb.AddPage(mf.page1, "Testseite 1")
        run(mf.nb)
        app.MainLoop()