Basj Basj - 3 months ago 10
Python Question

wx.BoxSizer both VERTICAL and HORIZONTAL centered

I would like to center an element both vertically and horizontally with

wx.BoxSizer
. I tried this unsuccessfuly (result: the element is centered vertically but not horizontally...) :

vsizer = wx.BoxSizer(wx.VERTICAL)
hsizer = wx.BoxSizer(wx.HORIZONTAL)
vsizer.AddStretchSpacer(1)
vsizer.Add(hsizer, 0, wx.ALL, 15)
vsizer.AddStretchSpacer(1)
self.SetSizer(vsizer)
hsizer.AddStretchSpacer(1)
hsizer.Add(wx.StaticBitmap(self, -1, myimg), 0, wx.ALL, 15)
hsizer.AddStretchSpacer(1)


How to center an element both vertically and horizontally with
wx.BoxSizer
?

Answer

Here is a simple example:

import wx

class Frame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "Vertical center")
        self.text = wx.StaticText(self, label=("This should be centered both"
                                   " vertically and horizontally"))
        sizer_v = wx.BoxSizer(wx.VERTICAL)
        sizer_h = wx.BoxSizer(wx.HORIZONTAL)
        sizer_h.Add(self.text, 1, wx.CENTER)
        sizer_v.Add(sizer_h, 1, wx.CENTER)
        self.SetSizer(sizer_v)

        self.Show()

app = wx.App()
Frame()
app.MainLoop()

wx.CENTER centers an element inside wx.BoxSizer (scroll to the bottom of the page): http://wiki.wxpython.org/BoxSizerTutorial
HTH

Comments