pythonuser-interfacewxpythonalignmentboxsizer

wxPython. How do I center a static size panel?


I know this is a very simple question but I've spent hours trying to figure out a solution. I want my panel to be a 50x50 blue box that doesn't change size, and stays centered in the window. I've tried having an inner and outer sizer that are HORIZONTAL and VERTICAL respectively and it seems to only recognize the outer sizer. I'd greatly appreciate it if anyone could help me out. import wx

class Main(wx.Frame):

def __init__(self,parent,id):
    wx.Frame.__init__(self,parent,id,'Main',size=(700,500))

    self.SetBackgroundColour('white')

    panel = wx.Panel(self,wx.ID_ANY,size=(50,50))
    panel.SetBackgroundColour('blue')

    sizer=wx.BoxSizer()
    sizer.Add(panel,0,wx.ALIGN_CENTER|wx.ALL)

    self.SetSizer(sizer)


if __name__=='__main__':
    app=wx.App()
    frame=Main(parent=None, id=-1)
    frame.Show()
    app.MainLoop()

Solution

  • Adding a stretchspacer on either side of the panel will do it

    import wx
    
    
    class Main(wx.Frame):
    
        def __init__(self, parent, id):
            wx.Frame.__init__(self, parent, id, 'Main', size=(700, 500))
    
            self.SetBackgroundColour('white')
    
            panel = wx.Panel(self, wx.ID_ANY, size=(50, 50))
            panel.SetBackgroundColour('blue')
    
            sizer = wx.BoxSizer()
            sizer.AddStretchSpacer(1)
            sizer.Add(panel, 0, wx.ALIGN_CENTER)
            sizer.AddStretchSpacer(1)
    
            self.SetSizer(sizer)
    
    
    if __name__ == '__main__':
        app = wx.App()
        frame = Main(parent=None, id=-1)
        frame.Show()
        app.MainLoop()