Search code examples
pythonpython-3.xwxpython

wxPython gridbagsizer colour


I'm testing with an application. Now I want to have a nice border around the mid panel, so it's embedded in another panel. However, when I want to add a gridbagsize in it and put static text components in it, it gets the colour of the main panel, not the midpanel. Obviously I'm doing something wrong...

Code:

    #Parent panel
    pnl = wx.Panel(self)
    pnl.SetBackgroundColour('#4f5049')

    vbox = wx.BoxSizer(wx.VERTICAL)

    midPan = wx.Panel(pnl)
    midPan.SetBackgroundColour('#ededed')

    vbox.Add(midPan,wx.ID_ANY, wx.EXPAND |wx.ALL, 20)

    sizer = wx.GridBagSizer(10,5)
    #sizer.
    st1=wx.StaticText(pnl,label='TEST')
    sizer.Add(st1, pos=(1,1),flag=wx.ALL,border=5)
    midPan.SetSizer(sizer)
    #vbox.Add(sizer,wx.ID_ANY, wx.EXPAND |wx.ALL, 0)
    #draw application       
    pnl.SetSizer(vbox)

enter image description here

as you see, it looks like the sizer is added to the pnl instead of the midPan... What am I doing wrong?


Solution

  • You are defining your statictext as a child of the pnl rather than midPan

    import wx
    
    class MyFrame(wx.Frame):
        def __init__(self, parent, id=wx.ID_ANY, title="", size=(360,100)):
            super(MyFrame, self).__init__(parent, id, title, size)
            pnl = wx.Panel(self)
            pnl.SetBackgroundColour('#4f5049')
    
            vbox = wx.BoxSizer(wx.VERTICAL)
    
            midPan = wx.Panel(pnl)
            midPan.SetBackgroundColour('green')
    
            vbox.Add(midPan,wx.ID_ANY, wx.EXPAND |wx.ALL, 20)
    
            sizer = wx.GridBagSizer(10,5)
            st1=wx.StaticText(midPan,label='Black on green')
            st2=wx.StaticText(midPan,label='White on green')
            st2.SetForegroundColour('white')
            st3=wx.StaticText(midPan)
            st3.SetLabelMarkup("<span foreground='black' background='red'>Black on red</span>")
            st4=wx.StaticText(midPan)
            st4.SetLabelMarkup("<span foreground='white' background='red'>White on red</span>")
    
            sizer.Add(st1, pos=(1,1),flag=wx.ALL,border=5)
            sizer.Add(st2, pos=(2,2),flag=wx.ALL,border=5)
            sizer.Add(st3, pos=(3,3),flag=wx.ALL,border=5)
            sizer.Add(st4, pos=(4,1),flag=wx.ALL,border=5)
    
            midPan.SetSizer(sizer)
            pnl.SetSizer(vbox)
            self.Show()
    
    if __name__ == "__main__":
        app = wx.App()
        frame = MyFrame(None,title="The Main Frame")
        app.MainLoop()
    

    enter image description here