Sizers (geometry control) in a wxPython GUI - a first example
Archive - Originally posted on "The Horse's Mouth" - 2010-12-15 18:00:09 - Graham Ellis
So today, I set out to write a really simple GUI in wxPython and make it as short as possible while showing
• Creation of components
• AUTOMATED component layout
• Handling of events on those components.
Here it is - 19 lines / 586 bytes:
import wx
class MyGrid(wx.Frame):
def __init__(self):
wx.Frame.__init__(self,None,-1,"First Sizer Demo")
grid = wx.GridSizer(rows=2, cols=2, hgap=20, vgap=30)
cellname = ("Angie","Babs","Cindy","Debbie-Alexandra")
for cell in range(len(cellname)):
current = wx.Button(self,cell+10,cellname[cell])
grid.Add(current,0,0)
self.Bind(wx.EVT_BUTTON,self.OnClick,current)
self.SetSizer(grid)
self.Fit()
def OnClick(self,event):
print event.GetId()
if event.GetId() == 11:
self.Destroy()
app = wx.PySimpleApp()
MyGrid().Show()
app.MainLoop()
COMMENTED source available [here]
My decision to automate the layout of the components is a significant one; I had the option of defining each of them by pixel position, but although that's more straightforward for your very first wxPython GUI, it also leads to longer and far less flexible code, and I recommend that you should use a Sizer in all but the most exceptional of circumstances. Of course, the example above just starts to touch on Sizers - you can choose from:
GridSizer (where rows and columns each have the same width and height)
FlexGridSizer (where each row and column is individually dimensioned)
GridBagSizer (where rows and colums are individually dimensioned, and you can have a widget spanning several rows and / or columns)
BoxSizer (where you have a single row or single column of widgets)
and you can nest sizers within sizers to give far greater flexibility - "almost any layout you like"
Going further, widgets won't always fill cells in your sizer, and you have a range of control as to the gravity of the widgets - whether they rise to the top of the call, fall to the bottom, or float in the middle. And you can also control whether the widgets expand to fill the cell, or are surrounded by background. If you look at the illustration at the top of this article, you'll see that the default is that the widgets gravitate to the top left of the cell.
Python has several GUIs available - but wxPython is perhaps the most popular, and we include a brief introduction in our Python Programming and Learning to program in Python courses. If you're going to be making heavy use of the wx GUI, and you're new to GUI programming, please ask us to extent the course by a day (which we can do for even one delegate) to introduce you to the wonderful art of designing and writing GUIs!