Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a WxPython panel item to expand

I have a WxPython frame containing a single item, such as:

class Panel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.text = wx.StaticText(self, label='Panel 1')

I have a frame containing several panels, including this one, and dimensions are ruled by sizers. I would like this StaticText to expand. Using a BoxSizer containing just the text and setting the wx.EXPAND flag does the trick, but it seems silly to use a sizer just for one item.

Any simpler solution?

(I could just add the StaticText to the parent frame's sizer directly, but for my design it makes more sense to start with a frame directly.)


I just realized that when creating a BoxSizer with one item doesn't work with wx.VERTICAL:

class Panel1(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.BackgroundColour = 'red'
        sizer = wx.BoxSizer(wx.VERTICAL)
        self.Sizer = sizer
        self.list = wx.ListBox(self, choices=[str(i) for i in xrange(100)])
        sizer.Add(self.list, 0, wx.EXPAND)
        sizer.Fit(self)

Of course it's ok with one item, but what if I want to add an item vertically later and still make both of them expand (e.g. when the user's window is expanded)?

Edit: ah, I just found out that proportion must be used in order to make boxsizers grow in both ways. (i.e., replace 0 with 1 in BoxSizer.Add's call.)

like image 675
Bastien Léonard Avatar asked Feb 27 '23 19:02

Bastien Léonard


1 Answers

A wx.Frame will automatically do this if it only has one child. However, a wx.Panel will not do this automatically. You're stuck using a sizer. If you find yourself doing it a lot, just make a convenience function:

def expanded(widget, padding=0):
    sizer = wx.BoxSizer(wx.VERTICAL)
    sizer.Add(widget, 1, wx.EXPAND|wx.ALL, padding)
    return sizer

class Panel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.text = wx.StaticText(self, label='Panel 1')
        self.SetSizer(expanded(self.text))

I threw the padding attribute in there as an extra bonus. Feel free to use it or ditch it.

like image 142
FogleBird Avatar answered Mar 07 '23 01:03

FogleBird