I’ve been a fan of wxFormBuilder for a a long time. It allows programmers like me to develop highly polished GUIs for Real World Applications or quick, temporary GUIs just to get the job done. To follow the below steps won’t take more than 15 minutes. The Goal is to build a usable calculator using wxPython and wxFoemBuilder
Things you’ll need
Any versions will do as long as they are inter compatible. I used Python 2.7.3 (32-bit), wxPython 22.214.171.124 (msw-unicode) and wxFormBuilder 3.2.3-beta (unicode)
Install all the above in thee order mentioned and we should be good to go.
Start wxFormBuilder and you’ll be greeted with New Project with a blank grey area in the center. Go to the Object Properties Window on the right and change name,file and set code generation to Python
Add a wxBoxSizer from Layout tab , make sure that orient is wxVERTICAL from the Object Properties
From the Common tab add TexCtrl and 2 Buttons.
Select each of these 3 elements and enable Expand and Stretch
Select the TextCtrl and change the name to text
Choose any button and rename it to solveButton and change the label to Solve
Similarly rename the other Button to clearButton and change OnButtonCick to clearFunc
Your window should be looking similar to this by now.
Save The Project and hit F8 to generate code. You should end up with a file called gui.py in the directory you saved in. This file holds the code for generating the graphics.
The final bit is writing the python code. Create a new python file in the same directory, and copy this code into it
Read the comments for explanation.
#importing wx files import wx #import the newly created GUI file import gui #importing * : to enable writing sin(13) instead of math.sin(13) from math import * #inherit from the MainFrame created in wxFowmBuilder and create CalcFrame class CalcFrame(gui.MainFrame): #constructor def __init__(self,parent): #initialize parent class gui.MainFrame.__init__(self,parent) #what to when 'Solve' is clicked #wx calls this function with and 'event' object def solveFunc(self,event): try: #evaluate the string in 'text' and put the answer back ans = eval(self.text.GetValue()) self.text.SetValue (str(ans)) except Exception: print 'error' #put a blank string in text when 'Clear' is clicked def clearFunc(self,event): self.text.SetValue(str('')) #mandatory in wx, create an app, False stands for not deteriction stdin/stdout #refer manual for details app = wx.App(False) #create an object of CalcFrame frame = CalcFrame(None) #show the frame frame.Show(True) #start the applications app.MainLoop()
The File contains less than 20 Lines of functional code.
All hail Python !!
If you are using IDLE on windows you can run this by clicking on Run Module and on Linux you can use python file.py where file.py is the file with the above contents. ( Thanks No more commandline )