Search code examples
wxpythonwxwidgets

How to specify proportions using wxPython's BoxSizer


I want to create a layout where one wxPanel takes up 2/3s of the window and one takes 1/3 of the window. I know how to make them 50/50 or how to specify minimum and maximum sizes. But is there a way to specify what proportion of the available space to take up?

import wx

eng = wx.App()
frame = wx.Frame(parent=None, title='wxPython')

main_panel = wx.Panel(frame)
main_panel.SetBackgroundColour(wx.Colour(255,0,0))
main_sizer = wx.BoxSizer(wx.HORIZONTAL)
main_panel.SetSizer(main_sizer)

left_panel = wx.Panel(main_panel)
left_panel.SetBackgroundColour(wx.Colour(0,255,0))
main_sizer.Add(left_panel, 1, wx.ALL | wx.EXPAND, 0)

right_panel = wx.Panel(main_panel)
right_panel.SetBackgroundColour(wx.Colour(0,0,255))
main_sizer.Add(right_panel, 1, wx.ALL | wx.EXPAND, 0)

frame.Show()
frame.CenterOnScreen()

eng.MainLoop()

Solution

  • The proportion parameter to the sizer will control this for you.

    Change the proportion value to one of the sizers entries to 2, it will make the sizer allot twice as much space to that entry.

    The proportion defines how large the sizer’s children are in relation to each other. In a vertical sizer, this changes the height; in a horizontal sizer, this changes the width.

    enter image description here

    Here, the righthand panel has been amended.

    import wx
    
    eng = wx.App()
    frame = wx.Frame(parent=None, title='wxPython')
    
    main_panel = wx.Panel(frame)
    main_panel.SetBackgroundColour(wx.Colour(255,0,0))
    main_sizer = wx.BoxSizer(wx.HORIZONTAL)
    main_panel.SetSizer(main_sizer)
    
    left_panel = wx.Panel(main_panel)
    left_panel.SetBackgroundColour(wx.Colour(0,255,0))
    main_sizer.Add(left_panel, 1, wx.ALL | wx.EXPAND, 0)
    
    right_panel = wx.Panel(main_panel)
    right_panel.SetBackgroundColour(wx.Colour(0,0,255))
    main_sizer.Add(right_panel, 2, wx.ALL | wx.EXPAND, 0)
    
    frame.Show()
    frame.CenterOnScreen()
    
    eng.MainLoop()