Search code examples
pythonwxpythonpanelcentersizer

wxpython: centering text within a panel within a sizer


It seems to me that the following code should display text right in the centre of the window; that is, in the centre of the inner panel. It doesn't however, and I'm wondering why not. If you run the code, you'll see a white panel in the middle of the frame, 150px by 150px. I do not want this area to change in size at all, but when I go about adding some text (uncommenting the txt variable in the middle of the snippet)the panel invariably shrinks to fit the text. Even specifying the size of the StaticText to match the panel isn't a solution because the text doesn't then centre-align.

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)




        self.rootPanel = wx.Panel(self)

        innerPanel = wx.Panel(self.rootPanel,-1, size=(150,150), style=wx.ALIGN_CENTER)
        innerPanel.SetBackgroundColour('WHITE')
        hbox = wx.BoxSizer(wx.HORIZONTAL) 
        vbox = wx.BoxSizer(wx.VERTICAL)

        # I want this line visible in the CENTRE of the inner panel
        #txt = wx.StaticText(innerPanel, id=-1, label="TEXT HERE",style=wx.ALIGN_CENTER, name="")

        hbox.Add(innerPanel, 0, wx.ALL|wx.ALIGN_CENTER)
        vbox.Add(hbox, 1, wx.ALL|wx.ALIGN_CENTER, 5)

        self.rootPanel.SetSizer(vbox)
        vbox.Fit(self)

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'wxBoxSizer.py')
        frame.Show(True)
        frame.Center()
        return True

app = MyApp(0)
app.MainLoop()

Solution

  • You just need to add a couple spacers to make it work.

    import wx
    
    class MyFrame(wx.Frame):
        def __init__(self, parent, id, title):
            wx.Frame.__init__(self, parent, id, title)
    
            self.rootPanel = wx.Panel(self)
    
            innerPanel = wx.Panel(self.rootPanel,-1, size=(150,150), style=wx.ALIGN_CENTER)
            innerPanel.SetBackgroundColour('WHITE')
            hbox = wx.BoxSizer(wx.HORIZONTAL) 
            vbox = wx.BoxSizer(wx.VERTICAL)
            innerBox = wx.BoxSizer(wx.VERTICAL)
    
            # I want this line visible in the CENTRE of the inner panel
            txt = wx.StaticText(innerPanel, id=-1, label="TEXT HERE",style=wx.ALIGN_CENTER, name="")
            innerBox.AddSpacer((150,75))
            innerBox.Add(txt, 0, wx.CENTER)
            innerBox.AddSpacer((150,75))
            innerPanel.SetSizer(innerBox)
    
            hbox.Add(innerPanel, 0, wx.ALL|wx.ALIGN_CENTER)
            vbox.Add(hbox, 1, wx.ALL|wx.ALIGN_CENTER, 5)
    
            self.rootPanel.SetSizer(vbox)
            vbox.Fit(self)
    
    class MyApp(wx.App):
        def OnInit(self):
            frame = MyFrame(None, -1, 'wxBoxSizer.py')
            frame.Show(True)
            frame.Center()
            return True
    
    app = MyApp(0)
    app.MainLoop()