Main Content

wxPython geometry - BoxSizer example

Archive - Originally posted on "The Horse's Mouth" - 2010-12-17 20:33:19 - Graham Ellis

Rather than manually position each of your widgets in a window in wxPython, you can use a Sizer; there are various type of GridSizer that let you define rows and columns of widgets, and there's a BoxSizer which lets you set up either a single row or a single column. Here's a single column example.

Components are created using regular wxPython widget constructors, and then we use the Add method on the BoxSizer to add them to the column. When all the components have been added, we set the sizer in the current wx.Frame, and then use the Fit method to adjust the frame to provide just enough space for the Sizer.

As buttons are pressed - playing a "take away" game in our example - the text label are changed to provide the full GUI feedback; thus you're seeing widget defintions, placement and events all in the one demo. We've also used parameters such as wx.EXPAND to fill the buttons to the width of the window, and as we Added each component we specified a weight with it, so that when I expanded the window each of the widget's areas expands in proportion (the ratio is 1:1:1:1:1:2 between the five buttons are the text area). Full source code [here].

This example has been kept short and easy so that you can learn from it / see what's happening. As the requirements of the GUI become more sophisticated, you can 'nest' sizers within sizers, and by doing so you're limited only by your ingenuity.