HomePython Page 3 - Designing a Calculator in wxPython
Creating the Layout - Python
wxPython is a library that makes it easy for Python programmers to build graphical user interfaces. Over the past few weeks, you have seen some articles covering this library. This week, you will learn how to create a simple but useful application with wxPython.
Let's start with a frame and make our way forward. Go ahead and put down the basics:
from wxPython.wx import *
class CalculatorFrame ( wxFrame ):
def __init__ ( self ):
wxFrame.__init__ ( self, None, -1, 'PyCalc' )
self.Show ( True )
calculator = wxPySimpleApp()
CalculatorFrame()
calculator.MainLoop()
Now we'll add the wxGridBagSizer and the display. Borders of 1 and 1 look good with our calculator, though you can pick whatever reasonable (or unreasonable) value you want:
If you execute our calculator, it looks horrid, but I promise you that things will improve once we're finished. Next come the buttons. Instead of calling wxGridBagSizer's Add method over a dozen times, we'll create a list for our buttons. The list will contain one list for each row. These lists will contain one list for each button, which will contain the button's text and the button's ID number. For spaces we do not want to occupy with buttons, we will put in None. This may sound complicated in a paragraph, but it makes a lot more sense when we put it in Python. We will then add everything to the grid with a loop: