wx.Panel scales to fit entire parent Frame despite

2019-06-23 19:13发布

问题:

I am a newbie to wxpython. I am trying to have a Frame and within that a small panel area which I am coloring blue. However no matter what I do the wx.Panel using the size attribute, the single panel snaps to the size of its parent frame. If I add another panel (pane2 in code below) both panes are drawn in the correct size.

I know I can control these panels using sizers. But I was trying to understand why the wx.Panel bject behaves the way it does when it's all alone.

Here is the code:

import wx

    class PlateGui(wx.Frame):

    def __init__(self, *args , **kwds):
        self.frame = wx.Frame.__init__(self,*args, **kwds)
        print "Made frame"


if __name__ == "__main__":
    an_app = wx.PySimpleApp()
    aframe = PlateGui(parent=None,id=-1,title="Test Frame",size=(300, 300))
    pane = wx.Panel(parent=aframe,size=(100,100),style=wx.RAISED_BORDER)
    pane.SetBackgroundColour(wx.Colour(0,0,255))
 #  pane2 = wx.Panel(parent=aframe,size=(200,100),style=wx.RAISED_BORDER)
 # Commenting out the second pane makes the first pane fit 
 # entire frame regardless of size specified  
    aframe.Show()
    an_app.MainLoop()

回答1:

By default, wx.Frame has a sizer that expands its child to fill the frame. Create your own sizer, add the panel to it (without specifying expand flags) and set that as the frame's sizer.

import wx
app = wx.PySimpleApp()
frame = wx.Frame(None, -1, 'Test')
sizer = wx.BoxSizer(wx.VERTICAL)
panel = wx.Panel(frame, -1, size=(100,100), style=wx.BORDER_RAISED)
sizer.Add(panel)
frame.SetSizer(sizer)
frame.Show()
app.MainLoop()


标签: wxpython