Getting a WxPython panel item to expand

我们两清 提交于 2020-01-03 18:49:06

问题


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.)


回答1:


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.



来源:https://stackoverflow.com/questions/3104323/getting-a-wxpython-panel-item-to-expand

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!