How to create a calculator - Part 2 (Phoenix)

Keywords : Calculator.


Demonstrating :

Tested py3.x, wx4.x and Win10.

Are you ready to use some samples ? ;)

Test, modify, correct, complete, improve and share your discoveries ! (!)


Sample one

img_sample_one.png

   1 # sample_one.py
   2 # Author : komoto48g
   3 # https://discuss.wxpython.org/t/i-made-a-calculator-with-20-lines-of-code-using-wx/35453
   4 
   5 """
   6 
   7 I made a Calculator with 20 lines of code using wx.
   8 
   9 I upgraded this within 20 lines
  10 (I had to ignored PEP8:multiple imports on one line).
  11 
  12 """
  13 
  14 import wx, wx.py.shell
  15 
  16 def pack(items, orient=wx.HORIZONTAL):
  17     sizer = wx.BoxSizer(orient)
  18     for item in items:
  19         sizer.Add(item, 1, wx.EXPAND|wx.ALL, 0)
  20     return sizer
  21 
  22 def bt_press(key):
  23     if   key == 'C': disp.clearCommand()
  24     elif key == '<': disp.DeleteBack()
  25     elif key == '=': disp.Execute(disp.getCommand())
  26     else           : disp.write(key)
  27 
  28 app = wx.App()
  29 self = wx.Frame(None, title="wxcalc ver.2")
  30 
  31 keys = '()C<789/456*123-.0=+'
  32 btns = [[wx.Button(self, label=c) for c in keys[i:i+4]] for i in range(0,20,4)]
  33 disp = wx.py.shell.Shell(self)
  34 
  35 self.Bind(wx.EVT_BUTTON, lambda v: bt_press(v.EventObject.Label) or disp.SetFocus())
  36 self.SetSizer(pack([disp] + [pack(x) for x in btns], orient=wx.VERTICAL))
  37 self.Show()
  38 app.MainLoop()


Sample two

img_sample_two.png

   1 # sample_two.py
   2 # Author : da-dada
   3 # https://discuss.wxpython.org/t/i-made-a-calculator-with-20-lines-of-code-using-wx/35453
   4 
   5 """
   6 
   7 I made a Calculator with 20 lines of code using wx.
   8 
   9 I upgraded this within 20 lines
  10 (I had to ignored PEP8:multiple imports on one line).
  11 
  12 """
  13 
  14 import wx
  15 
  16 def pack(items, orient=wx.HORIZONTAL):
  17     sizer = wx.BoxSizer(orient)
  18     sizer.AddMany([(i, 1, wx.EXPAND | wx.ALL, 0) for i in items])
  19     return sizer
  20 
  21 def bt_press(key):
  22     disp.Value = {'C': lambda v: '', '<': lambda v: v[:-1], '=': lambda v: str(round(eval(v),16))}[key](disp.Value) if key in ['C','=','<'] else (disp.Value + key)
  23 
  24 app, self = wx.App(), wx.Frame(None, title="wxcalc")
  25 disp = wx.TextCtrl(self)
  26 
  27 self.Bind(wx.EVT_BUTTON, lambda v: bt_press(v.EventObject.Label))
  28 self.SetSizer(pack([disp] + [pack(x) for x in [[wx.Button(self, label=c) for c in '()C<789/456*123-.0=+'[i:i+4]] for i in range(0,20,4)]], orient=wx.VERTICAL))
  29 self.Show()
  30 app.MainLoop()


Sample three

img_sample_three.png

   1 # !/usr/bin/env python3
   2 # -*- coding : utf-8 -*-
   3 
   4 # sample_three.py
   5 # Megumi221
   6 # https://ideal-user-interface.hatenablog.com/entry/20090711/1247328263
   7 
   8 # BritishUnit.py                                  (2009/07/11 23:58:30)
   9 #------------------------------------------------------------------------
  10 import wx
  11 import os, sys
  12 import time
  13 
  14 # French conversion :
  15 # Length      = Longueur
  16 # Area        = Aire
  17 # Velocity    = Vitesse
  18 # Mass        = Masse
  19 # Energy      = Énergie
  20 # Temperature = Température
  21 # Density     = Densité
  22 # Mass flux   = Flux massique
  23 # Enthalpy    = Enthalpie
  24 # Pressure    = Pression
  25 # Heat        = Chaleur
  26 
  27 
  28 ChoiceList = ["Length [ft]", "Area [ft^2]", "Velocity [ft/s]",
  29               "Mass [lbm]", "Energy [Btu]", "Temperature [F]",
  30               "Density [lbm/ft^3]", "Mass flux [lbm/s]", "Enthalpy [Btu/lbm]",
  31               "Pressure [psia]", "Pressure [lbf/ft^2]", "Heat [Btu/s]"]
  32 
  33 SIList = ["[m]", "[m^2]", "[m/s]",
  34           "[kg]", "[kJ]", "[C]",
  35           "[kg/m^3]", "[kg/s]", "[kJ/kg]",
  36           "[Pa]", "[Pa]", "[W]"]
  37 
  38 coeff = [0.3048, 0.3048**2, 0.3048,
  39          0.45359237, 1.055, 5.0/9.0,
  40          0.45359237/(0.3048)**3, 0.45359237, 1.055/0.45359237,
  41          703.07*9806.65, 4.44822/(0.3048)**2, 1055.0]
  42 
  43 bb = [0.0, 0.0, 0.0,
  44       0.0, 0.0, 32.0,
  45       0.0, 0.0, 0.0,
  46       0.0, 0.0, 0.0]
  47 
  48 
  49 class MainFrame(wx.Frame):
  50     def __init__(self, id, title):
  51         width, height = 480,130
  52         wx.Frame.__init__(self, id, title="Changing unit",
  53                           size=wx.Size(width, height))
  54 
  55         _icon = wx.Icon('icons/wxwin.ico', wx.BITMAP_TYPE_ICO)
  56         self.SetIcon(_icon)
  57 
  58         Pan = wx.Panel(self, -1)
  59 
  60         self.Chce = wx.Choice(Pan, -1, choices=ChoiceList)
  61         self.TxtCtl = wx.TextCtrl(Pan, -1, "Enter a value", size=(130,-1))
  62         self.StTxt1 = wx.StaticText(Pan, -1, " =  ")
  63         self.Btn = wx.Button(Pan, -1, "&Convert")  # 換算する
  64 
  65         self.Chce.Bind(wx.EVT_CHOICE, self.OnChoice)
  66         self.Btn.Bind(wx.EVT_BUTTON, self.ConvUnit)
  67 
  68         vsizer0 = wx.BoxSizer(wx.VERTICAL)
  69         hsizer1 = wx.BoxSizer(wx.HORIZONTAL)
  70         hsizer1.Add(self.TxtCtl, 0, wx.ALIGN_LEFT|wx.ALL, 5)
  71         hsizer1.Add(self.Chce, 0, wx.ALIGN_LEFT|wx.ALL, 5)
  72         hsizer1.Add(self.StTxt1, 0, wx.ALIGN_LEFT|wx.ALL, 5)
  73         vsizer0.Add(hsizer1,0, wx.ALIGN_LEFT|wx.ALL, 5)
  74         vsizer0.Add(self.Btn,0, wx.ALIGN_LEFT|wx.ALL, 10)
  75         Pan.SetSizer(vsizer0)
  76         vsizer0.Fit(Pan)
  77 
  78 
  79     def OnChoice(self, event):
  80         pass
  81 
  82 
  83     def ConvUnit(self, event):
  84         BtVal= float(self.TxtCtl.GetValue())
  85         CNum = self.Chce.GetSelection()
  86         SiVal= (BtVal-bb[CNum])*coeff[CNum]
  87         newString = "= " + str(SiVal) + SIList[CNum]
  88         self.StTxt1.SetLabel(newString)
  89 
  90 
  91 class Application(wx.App):
  92     def OnInit(self):
  93         frame = MainFrame(None, -1)
  94         frame.Show(True)
  95         self.SetTopWindow(frame)
  96         return True
  97 
  98 
  99 def main():
 100     app = Application(0)
 101     app.MainLoop()
 102 
 103 
 104 if __name__ == '__main__':
 105     main()


Sample four

img_sample_four.png

   1 # sample_four.py
   2 # https://codingshiksha.com/python/python-3-wxpython-temperature-converter-celsius-kelvin-fahrenheit-gui-script-desktop-app-full-project-for-beginners/
   3 
   4 import wx
   5 
   6 def temperature_converter(value, convert_from, convert_to):
   7 
   8     def celsius_converter(value, convert_to):
   9         """
  10         Converts from Celsius to Fahrenheit or Kelvin.
  11         """
  12         if convert_to == "°F":
  13             return f"{str((round(value * 9/5 + 32, 2)))} {convert_to}"
  14         elif convert_to == "K":
  15             return f"{str(round((value + 273.15), 2))} {convert_to}"
  16 
  17     def fahrenheit_converter(value, convert_to):
  18         """
  19         Converts from Fahrenheit to Celsius or Kelvin.
  20         """
  21         if convert_to == "°C":
  22             return f"{str(round((value - 32) * 5/9, 2))} {convert_to}"
  23         elif convert_to == "K":
  24             return f"{str(round((value - 32) * 5/9 + 273.15, 2))} {convert_to}"
  25 
  26     def kelvin_converter(value, convert_to):
  27         """
  28         Converts from Kelvin to Celsius or Fahrenheit.
  29         """
  30         if convert_to == "°C":
  31             return f"{str(round(value - 273.15, 2))} {convert_to}"
  32         elif convert_to == "°F":
  33             return f"{str(round((value - 273.15) * 9/5 + 32, 2))} {convert_to}"
  34 
  35     converters = {"°C": celsius_converter(value, convert_to),
  36                   "°F": fahrenheit_converter(value, convert_to),
  37                   "K": kelvin_converter(value, convert_to)
  38                   }
  39     return converters[convert_from]
  40 
  41 #-------------------------------------------------------------------------------
  42 
  43 class TempConverterInterface(wx.Frame):
  44     def __init__(self, parent, style, title):
  45         super().__init__(parent, style=style, title=title, size=(310, 200))
  46 
  47         self.InitUI()
  48         self.Centre()
  49         self.Show()
  50 
  51     def InitUI(self):
  52 
  53         panel = wx.Panel(self)
  54         font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT)
  55         font.SetPointSize(9)
  56         hbox = wx.BoxSizer(wx.VERTICAL)
  57 
  58         fgs = wx.FlexGridSizer(rows=4, cols=2, vgap=10, hgap=15)
  59 
  60         temp_value = wx.StaticText(panel, label="Temperature Value : ")
  61         temp_value.SetFont(font)
  62         from_temp = wx.StaticText(panel, label="From : ")
  63         from_temp.SetFont(font)
  64         to_temp = wx.StaticText(panel, label="To : ")
  65         to_temp.SetFont(font)
  66         calc_button = wx.Button(panel, label="&Calculate")
  67         calc_button.Bind(wx.EVT_BUTTON, self.on_press_calculate)
  68         self.result = wx.StaticText(panel, label='', pos=(10, 10))
  69         font.SetPointSize(14)
  70         self.result.SetFont(font)
  71 
  72         self.tc1 = wx.TextCtrl(panel)
  73         self.tc2_combo = wx.ComboBox(
  74             panel, choices=["°C", "°F", "K"], style=wx.CB_READONLY)
  75         self.tc3_combo = wx.ComboBox(
  76             panel, choices=["°C", "°F", "K"], style=wx.CB_READONLY)
  77 
  78         fgs.AddMany([(temp_value), (self.tc1, 1, wx.EXPAND), (from_temp),
  79                      (self.tc2_combo, 1, wx.EXPAND), (to_temp, 1,
  80                                                       wx.EXPAND), (self.tc3_combo, 1, wx.EXPAND), (calc_button),
  81                      (self.result, 1, wx.RIGHT)])
  82 
  83         hbox.Add(fgs, proportion=1, flag=wx.ALL | wx.EXPAND, border=15)
  84 
  85         panel.SetSizer(hbox)
  86 
  87     def ShowValueErrorMessage(self):
  88         wx.MessageBox('You entered an invalid value.', 'Value Error',
  89                       style=wx.OK | wx.ICON_ERROR)
  90 
  91     def ShowTypeErrorMessage(self):
  92         wx.MessageBox('Origin and final temperature units must be different.', 'Unit Type Error',
  93                       style=wx.OK | wx.ICON_ERROR)
  94 
  95     def on_press_calculate(self, event):
  96         try:
  97             self.result.Label = temperature_converter(value=float(self.tc1.GetValue()),
  98                                                       convert_from=self.tc2_combo.GetValue(),
  99                                                       convert_to=self.tc3_combo.GetValue())
 100         except ValueError:
 101             self.ShowValueErrorMessage()
 102         except TypeError:
 103             self.ShowTypeErrorMessage()
 104 
 105 #-------------------------------------------------------------------------------
 106 
 107 def main():
 108 
 109     app = wx.App()
 110     frame = TempConverterInterface(None, style=wx.MINIMIZE_BOX |
 111                                    wx.SYSTEM_MENU | wx.CAPTION |
 112                                    wx.CLOSE_BOX,
 113                                    title='Temperature Converter')
 114     frame.Show()
 115     app.MainLoop()
 116 
 117 
 118 if __name__ == '__main__':
 119     main()


Sample five

img_sample_five.png

   1 # sample_five.py
   2 
   3 '''
   4 Created on Dec 30, 2013
   5 
   6 @author: Tuna
   7 '''
   8 
   9 import wx
  10 
  11 title1 = """
  12 This program will calculate your BMI
  13 (Body Mass Index) based on
  14 your height and weight.
  15 """
  16 
  17 title2 = """
  18 Here is the BMI Range :
  19 Very severely underweight : 0-14.9
  20 Severly underweight : 15-15.9
  21 Underweight : 16-17.9
  22 Normal (healthy weight) : 18-24.9
  23 Overweight : 25-29.9
  24 Moderately obese : 30-34.9
  25 Severely obese : 35-39.9
  26 Very severely obese : 40+
  27 """
  28 
  29 #-------------------------------------------------------------------------------
  30 
  31 class User():
  32 
  33     def __init__(self):
  34         self.bmi_dict = {
  35             'very severely underweight': [0,150],
  36             'severly underweight':[150,160],
  37             'underweight':[160,180],
  38             'normal (healthy weight)':[180,250],
  39             'overweight':[250,300],
  40             'moderately obese':[300,350],
  41             'severely obese':[350,400],
  42             'very severely obese':[400,1000]
  43             }
  44 
  45     def bmi_calc(self):
  46         if self.height=='0':
  47             return 0
  48         else:
  49             return (float(self.weight)/(float(self.height)**2))*703
  50 
  51     def category(self):
  52         for cat in self.bmi_dict:
  53             updbmi = int(round(self.bmi*10))
  54             if updbmi in range(self.bmi_dict[cat][0],self.bmi_dict[cat][1]):
  55                 return cat
  56         return None
  57 
  58 #===============================================================================
  59 # test1=User()
  60 # test1.weight=270
  61 # test1.height=73
  62 # test1.bmi=test1.bmi_calc()
  63 # test1.bmi=int(round(test1.bmi,0))
  64 # assert(test1.bmi==36)
  65 # test1.bmi_category=test1.category()
  66 # assert(test1.bmi_category=='severely obese')
  67 #
  68 # test2=User()
  69 # test2.weight=130
  70 # test2.height=65
  71 # test2.bmi=test2.bmi_calc()
  72 # test2.bmi=int(round(test2.bmi,0))
  73 # assert(test2.bmi==22)
  74 # test2.bmi_category=test2.category()
  75 # assert(test2.bmi_category=='normal (healthy weight)')
  76 #===============================================================================
  77 
  78 class RootApp(wx.Frame):
  79     def closewindow(self, event):
  80         '''Upon click of red X'''
  81         self.Destroy()
  82 
  83 
  84     def bmiFind(self, event):
  85         self.user = User()
  86         self.weight = self.tc3.GetValue()
  87         self.user.weight = self.weight
  88         self.height = self.tc4.GetValue()
  89         self.user.height = self.height
  90         self.bmi = self.user.bmi_calc()
  91         self.user.bmi = self.bmi
  92         self.st5.SetLabel("Your BMI is " + str(int(self.bmi)) + ".")
  93         self.category = self.user.category()
  94         self.st6.SetLabel("You are " + self.category + ".")
  95 
  96 
  97     def __init__(self, parent, id):
  98         wx.Frame.__init__(self, parent, id, title="BMI Calculator v0.1", size=(250, 385))
  99 
 100         panel = wx.Panel(self)
 101         vbox = wx.BoxSizer(wx.VERTICAL)
 102 
 103         '''Create BMI.User object'''
 104 
 105         st8 = wx.StaticText(panel, label=title1, style=wx.ALIGN_CENTRE_HORIZONTAL)
 106 
 107         st9 = wx.StaticText(panel, label=title2)
 108 
 109         '''Name'''
 110 
 111         '''Age'''
 112 
 113         '''Weight'''
 114 
 115         hbox3 = wx.BoxSizer(wx.HORIZONTAL)
 116         st3a = wx.StaticText(panel, label='Weight :')
 117         hbox3.Add(st3a, flag=wx.RIGHT, border=80)
 118         self.tc3 = wx.TextCtrl(panel, value='0')
 119         hbox3.Add(self.tc3, proportion=1, flag=wx.LEFT|wx.RIGHT, border=10)
 120         st3b = wx.StaticText(panel, label='lbs')
 121         hbox3.Add(st3b, flag=wx.RIGHT, border=10)
 122 
 123         '''Height'''
 124 
 125         hbox4 = wx.BoxSizer(wx.HORIZONTAL)
 126         st4a = wx.StaticText(panel, label='Height :')
 127         hbox4.Add(st4a, flag=wx.RIGHT, border=83)
 128         self.tc4 = wx.TextCtrl(panel, value='0')
 129         hbox4.Add(self.tc4, proportion=1, flag=wx.LEFT|wx.RIGHT, border=10)
 130         st4b = wx.StaticText(panel, label='inches')
 131         hbox4.Add(st4b, flag=wx.RIGHT, border=10)
 132 
 133         '''BMI result'''
 134 
 135         hbox5 = wx.BoxSizer(wx.HORIZONTAL)
 136         self.st5 = wx.StaticText(panel, label='')
 137         hbox5.Add(self.st5)
 138 
 139         '''BMI Category result'''
 140 
 141         hbox6 = wx.BoxSizer(wx.HORIZONTAL)
 142         self.st6 = wx.StaticText(panel, label='')
 143         hbox6.Add(self.st6)
 144 
 145         '''Calculate Button'''
 146 
 147         hbox7 = wx.BoxSizer(wx.HORIZONTAL)
 148         buttonCalc = wx.Button(panel, wx.ID_ANY, label='&Calculate BMI', size=(220,25))
 149         hbox7.Add(buttonCalc, flag=wx.EXPAND)
 150 
 151         '''Bind Buttons'''
 152 
 153         self.Bind(wx.EVT_CLOSE, self.closewindow)
 154         self.Bind(wx.EVT_BUTTON, self.bmiFind, source=buttonCalc)
 155 
 156         '''Add horizontal boxes to vertical box'''
 157 
 158         vbox.Add(st8, flag=wx.EXPAND|wx.TOP|wx.LEFT|wx.BOTTOM, border=10)
 159         vbox.Add(st9, flag=wx.EXPAND|wx.TOP|wx.LEFT, border=10)
 160         vbox.Add((-1,10))
 161         vbox.Add(hbox3, flag=wx.EXPAND|wx.LEFT|wx.BOTTOM, border=10)
 162         vbox.Add(hbox4, flag=wx.EXPAND|wx.LEFT|wx.BOTTOM, border=10)
 163         vbox.Add(hbox5, flag=wx.EXPAND|wx.LEFT|wx.BOTTOM, border=10)
 164         vbox.Add(hbox6, flag=wx.EXPAND|wx.LEFT|wx.BOTTOM, border=10)
 165         vbox.Add(hbox7, flag=wx.EXPAND|wx.LEFT|wx.BOTTOM, border=10)
 166         panel.SetSizer(vbox)
 167 
 168 #-------------------------------------------------------------------------------
 169 
 170 if __name__=='__main__':
 171     app = wx.App()
 172     frame = RootApp(parent=None, id=-1)
 173     frame.SetSize(500, 500)
 174     frame.CentreOnScreen()
 175     #frame.Move((1450,500))
 176     frame.Show()
 177     app.MainLoop()


Sample six

[ATTACH]

   1 # sample_six.py


Sample seven

[ATTACH]

   1 # sample_seven.py


Sample eight

[ATTACH]

   1 # sample_eight.py


Sample nine

[ATTACH]

   1 # sample_nine.py


Sample ten

[ATTACH]

   1 # sample_ten.py


Sample eleven

[ATTACH]

   1 # sample_eleven.py


Download source

source.zip


Additional Information

Link :

- - - - -

https://wiki.wxpython.org/TitleIndex

https://docs.wxpython.org/


Thanks to

komoto48g (sample_one.py coding), da-dada (sample_two.py coding), Megumi221 (sample_three.py), codingshiksha (sample_four.py), Tuna (sample_five.py), the wxPython community...


About this page

Date(d/m/y) Person (bot) Comments :

14/01/23 - Ecco (Created page for wxPython Phoenix).


Comments

- blah, blah, blah....

How to create a calculator - Part 2 (Phoenix) (last edited 2023-01-14 15:23:56 by Ecco)

NOTE: To edit pages in this wiki you must be a member of the TrustedEditorsGroup.