wxPython - Layout Management

A GUI widget can be placed inside the container window by specifying its absolute coordinates measured in pixels. The coordinates are relative to the dimensions of the window defined by size argument of its constructor. Position of the widget inside the window is defined by pos argument of its constructor.

import wx  

app = wx.App() 
window = wx.Frame(None, title = "wxPython Frame", size = (300,200)) 
panel = wx.Panel(window) 
label = wx.StaticText(panel, label = "Hello World", pos = (100,50)) 

This Absolute Positioning however is not suitable because of the following reasons −

  • The position of the widget does not change even if the window is resized.

  • The appearance may not be uniform on different display devices with different resolutions.

  • Modification in the layout is difficult as it may need redesigning the entire form.

wxPython API provides Layout classes for more elegant management of positioning of widgets inside the container. The advantages of Layout managers over absolute positioning are −

  • Widgets inside the window are automatically resized.
  • Ensures uniform appearance on display devices with different resolutions.
  • Adding or removing widgets dynamically is possible without having to redesign.

Layout manager is called Sizer in wxPython. Wx.Sizer is the base class for all sizer subclasses. Let us discuss some of the important sizers such as wx.BoxSizer, wx.StaticBoxSizer, wx.GridSizer, wx.FlexGridSizer, and wx.GridBagSizer.

S.N. Sizers & Description
1 BoxSizer

This sizer allows the controls to be arranged in row-wise or column-wise manner. BoxSizer’s layout is determined by its orientation argument (either wxVERTICAL or wxHORIZONTAL).

2 GridSizer

As the name suggests, a GridSizer object presents a two dimensional grid. Controls are added in the grid slot in the left-to-right and top-to-bottom order.

3 FlexiGridSizer

This sizer also has a two dimensional grid. However, it provides little more flexibility in laying out the controls in the cells.

4 GridBagSizer

GridBagSizer is a versatile sizer. It offers more enhancements than FlexiGridSizer. Child widget can be added to a specific cell within the grid.

5 StaticBoxSizer

A StaticBoxSizer puts a box sizer into a static box. It provides a border around the box along with a label at the top.