1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | from __future__ import division # So that 8/3 will be 2.6666 and not 2 import wx from math import * # So we can evaluate "sqrt(8)" class Calculator(wx.Dialog): '''Main calculator dialog''' def __init__( self ): wx.Dialog.__init__( self , None , - 1 , "Calculator" ) sizer = wx.BoxSizer(wx.VERTICAL) # Main vertical sizer # ____________v self .display = wx.ComboBox( self , - 1 ) # Current calculation sizer.Add( self .display, 0 , wx.EXPAND) # Add to main sizer # [7][8][9][/] # [4][5][6][*] # [1][2][3][-] # [0][.][C][+] gsizer = wx.GridSizer( 4 , 4 ) for row in (( "7" , "8" , "9" , "/" ), ( "4" , "5" , "6" , "*" ), ( "1" , "2" , "3" , "-" ), ( "0" , "." , "C" , "+" )): for label in row: b = wx.Button( self , - 1 , label) gsizer.Add(b) self .Bind(wx.EVT_BUTTON, self .OnButton, b) sizer.Add(gsizer, 1 , wx.EXPAND) # [ = ] b = wx.Button( self , - 1 , "=" ) self .Bind(wx.EVT_BUTTON, self .OnButton, b) sizer.Add(b, 0 , wx.EXPAND) self .equal = b # Set sizer and center self .SetSizer(sizer) sizer.Fit( self ) self .CenterOnScreen() def OnButton( self , evt): '''Handle button click event''' # Get title of clicked button label = evt.GetEventObject().GetLabel() if label = = "=" : # Calculate try : compute = self .display.GetValue() # Ignore empty calculation if not compute.strip(): return # Calculate result result = eval (compute) # Add to history self .display.Insert(compute, 0 ) # Show result self .display.SetValue( str (result)) except Exception, e: wx.LogError( str (e)) return elif label = = "C" : # Clear self .display.SetValue("") else : # Just add button text to current calculation self .display.SetValue( self .display.GetValue() + label) self .equal.SetFocus() # Set the [=] button in focus if __name__ = = "__main__" : # Run the application app = wx.App() dlg = Calculator() dlg.ShowModal() dlg.Destroy() |
article
Sunday, May 27, 2018
wxpython Calculator
wxpython Calculator