How to create a calculator - Part 1 (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 
   3 """
   4 
   5 Purpose : Create a customized calculator
   6 Author  : Jan Bodnar (zetcode.com)
   7         : Modified By Ecco - May 2021
   8 Link    : https://zetcode.com/wxpython/layout/
   9 
  10 """
  11 
  12 import os
  13 import wx
  14 
  15 # class MyCalculator
  16 # class MyFrame
  17 
  18 #-------------------------------------------------------------------------------
  19 
  20 class MyCalculator(wx.Frame):
  21     def __init__(self, parent, id, title):
  22         wx.Frame.__init__(self, parent,
  23                           -1, title,
  24                           style=wx.DEFAULT_FRAME_STYLE)
  25 
  26         #------------
  27         
  28         self.parent = parent
  29         self.formula = False
  30         
  31         #------------
  32         
  33         # Simplified init method
  34         self.SetProperties()
  35         self.CreateCtrls()
  36         self.MakeMenuBar()
  37         self.BindEvents()
  38         self.DoLayout()        
  39 
  40         #------------
  41 
  42         self.CenterOnParent()
  43         self.GetParent().Enable(False)
  44         self.Show(True)
  45 
  46         self.__eventLoop = wx.GUIEventLoop()
  47         self.__eventLoop.Run()
  48         
  49     #---------------------------------------------------------------------------
  50 
  51     def SetProperties(self):
  52         """
  53         Set the dialog properties (title, icon...).
  54         """
  55 
  56         # Set frame icon. 
  57         self.SetIcon(wx.Icon('icons/wxwin.ico'))
  58         self.SetSize((420, 300))
  59         self.SetMinSize((430, 310))
  60 
  61 
  62     def MakeMenuBar(self):
  63         """
  64         Make menu data.
  65         """
  66 
  67         menubar = wx.MenuBar()
  68 
  69         #------------
  70         
  71         menuFile = wx.Menu()
  72 
  73         #------------
  74 
  75         # Add a bitmap to "exitItem" menu.
  76         bmp = wx.Bitmap("bitmaps/item_quit.png", wx.BITMAP_TYPE_PNG)     
  77 
  78         exitItem = wx.MenuItem(parentMenu=menuFile,
  79                                id=22,
  80                                text="&Quit\tCtrl+Q",
  81                                helpString="Exit Calculator.",
  82                                kind=wx.ITEM_NORMAL,
  83                                subMenu=None)
  84         exitItem.SetBitmap(bmp)
  85         menuFile.Append(exitItem)
  86         
  87         #------------
  88         
  89         menubar.Append(menuFile, '&File')
  90 
  91         #------------
  92         
  93         self.SetMenuBar(menubar)
  94 
  95         
  96     def CreateCtrls(self):
  97         """
  98         ...    
  99         """
 100 
 101         # wx.Font(pointSize, family, style, weight, underline, faceName)
 102         font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
 103         font.SetWeight(wx.BOLD)
 104 
 105         #------------
 106         
 107         self.panel = wx.Panel(self, -1)
 108         
 109         self.display = wx.TextCtrl(self.panel,
 110                                    -1, '',
 111                                    style=wx.TE_RIGHT)
 112         self.display.SetBackgroundColour("#fded68") 
 113         self.display.SetForegroundColour("#0326f9")
 114         self.display.SetFocus()
 115         
 116         #------------
 117 
 118         self.btn1 = wx.Button(self.panel, 20, 'Clr')
 119         self.btn2 = wx.Button(self.panel, 21, 'Bck')
 120         self.txt3 = wx.StaticText(self.panel, -1, '')
 121         self.btn4 = wx.Button(self.panel, 22, '&Close')
 122         self.btn5 = wx.Button(self.panel, 1, '7')
 123         self.btn6 = wx.Button(self.panel, 2, '8')
 124         self.btn7 = wx.Button(self.panel, 3, '9')
 125         self.btn8 = wx.Button(self.panel, 4, '/')
 126         self.btn9 = wx.Button(self.panel, 5, '4')
 127         self.btn10 = wx.Button(self.panel, 6, '5')
 128         self.btn11 = wx.Button(self.panel, 7, '6')
 129         self.btn12 = wx.Button(self.panel, 8, '*')
 130         self.btn13 = wx.Button(self.panel, 9, '1')
 131         self.btn14 = wx.Button(self.panel, 10, '2')
 132         self.btn15 = wx.Button(self.panel, 11, '3')
 133         self.btn16 = wx.Button(self.panel, 12, '-')
 134         self.btn17 = wx.Button(self.panel, 13, '0')
 135         self.btn18 = wx.Button(self.panel, 14, '.')
 136         self.btn19 = wx.Button(self.panel, 15, '=')
 137         self.btn20 = wx.Button(self.panel, 16, '+')
 138 
 139         self.btn1.SetForegroundColour("#008B00")
 140         self.btn2.SetForegroundColour("blue")
 141         self.btn4.SetForegroundColour("red")
 142         self.btn5.SetForegroundColour("blue")
 143         self.btn6.SetForegroundColour("blue")
 144         self.btn7.SetForegroundColour("blue")
 145         self.btn8.SetForegroundColour("blue")
 146         self.btn9.SetForegroundColour("blue")
 147         self.btn10.SetForegroundColour("blue")
 148         self.btn11.SetForegroundColour("blue")
 149         self.btn12.SetForegroundColour("blue")
 150         self.btn13.SetForegroundColour("blue")
 151         self.btn14.SetForegroundColour("blue")
 152         self.btn15.SetForegroundColour("blue")
 153         self.btn16.SetForegroundColour("blue")
 154         self.btn17.SetForegroundColour("blue")
 155         self.btn18.SetForegroundColour("blue")
 156         self.btn20.SetForegroundColour("blue")
 157 
 158         self.panel.SetBackgroundColour("#cce8f2")        
 159         
 160         self.btn1.SetFont(font)
 161         self.btn2.SetFont(font)
 162         self.btn4.SetFont(font)
 163         self.btn19.SetFont(font)
 164         
 165         self.btn19.SetDefault()
 166         
 167 
 168     def BindEvents(self):
 169         """
 170         ...  
 171         """
 172         
 173         self.Bind(wx.EVT_BUTTON, self.OnClear, id=20)
 174         self.Bind(wx.EVT_BUTTON, self.OnBackspace, id=21)
 175         self.Bind(wx.EVT_BUTTON, self.OnClose, id=22)
 176         self.Bind(wx.EVT_BUTTON, self.OnSeven, id=1)
 177         self.Bind(wx.EVT_BUTTON, self.OnEight, id=2)
 178         self.Bind(wx.EVT_BUTTON, self.OnNine, id=3)
 179         self.Bind(wx.EVT_BUTTON, self.OnDivide, id=4)
 180         self.Bind(wx.EVT_BUTTON, self.OnFour, id=5)
 181         self.Bind(wx.EVT_BUTTON, self.OnFive, id=6)
 182         self.Bind(wx.EVT_BUTTON, self.OnSix, id=7)
 183         self.Bind(wx.EVT_BUTTON, self.OnMultiply, id=8)
 184         self.Bind(wx.EVT_BUTTON, self.OnOne, id=9)
 185         self.Bind(wx.EVT_BUTTON, self.OnTwo, id=10)
 186         self.Bind(wx.EVT_BUTTON, self.OnThree, id=11)
 187         self.Bind(wx.EVT_BUTTON, self.OnMinus, id=12)
 188         self.Bind(wx.EVT_BUTTON, self.OnZero, id=13)
 189         self.Bind(wx.EVT_BUTTON, self.OnDot, id=14)
 190         self.Bind(wx.EVT_BUTTON, self.OnEqual, id=15)
 191         self.Bind(wx.EVT_BUTTON, self.OnPlus, id=16)
 192 
 193         self.Bind(wx.EVT_MENU, self.OnClose, id=22)
 194 
 195         self.Bind(wx.EVT_CHAR_HOOK, self.OnKeyUp)
 196         
 197         # (Allows frame's title-bar close to work)
 198         self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) 
 199         
 200 
 201     def DoLayout(self):
 202         """
 203         ...    
 204         """
 205 
 206         # Sizers         
 207         # MainSizer is the top-level one that manages everything   
 208         mainSizer = wx.BoxSizer(wx.VERTICAL)
 209         gridSizer = wx.GridSizer(5, 4, 5, 5)
 210 
 211         #------------
 212 
 213         # Assign widgets to sizers
 214         mainSizer.Add(self.display, 0, wx.EXPAND | wx.ALL, 5)
 215 
 216         gridSizer.AddMany([(self.btn1, 1, wx.EXPAND),
 217                            (self.btn2, 1, wx.EXPAND),
 218                            (self.txt3, 1, wx.EXPAND),
 219                            (self.btn4, 1, wx.EXPAND),
 220                            (self.btn5, 1, wx.EXPAND),
 221                            (self.btn6, 1, wx.EXPAND),
 222                            (self.btn7, 1, wx.EXPAND),
 223                            (self.btn8, 1, wx.EXPAND),
 224                            (self.btn9, 1, wx.EXPAND),
 225                            (self.btn10, 1, wx.EXPAND),
 226                            (self.btn11, 1, wx.EXPAND),
 227                            (self.btn12, 1, wx.EXPAND),
 228                            (self.btn13, 1, wx.EXPAND),
 229                            (self.btn14, 1, wx.EXPAND),
 230                            (self.btn15, 1, wx.EXPAND),
 231                            (self.btn16, 1, wx.EXPAND),
 232                            (self.btn17, 1, wx.EXPAND),
 233                            (self.btn18, 1, wx.EXPAND),
 234                            (self.btn19, 1, wx.EXPAND),
 235                            (self.btn20, 1, wx.EXPAND)])
 236 
 237         # Assign to mainSizer the other sizers
 238         mainSizer.Add(gridSizer, 1, wx.EXPAND | wx.ALL, 5)
 239 
 240         #------------
 241         
 242         self.panel.SetSizer(mainSizer)
 243         mainSizer.Fit(self)
 244 
 245 
 246     def OnClear(self, event):
 247         """
 248         ...    
 249         """
 250                 
 251         self.display.Clear()
 252         self.display.SetFocus()
 253         
 254 
 255     def OnBackspace(self, event):
 256         """
 257         ...    
 258         """
 259         
 260         formula = self.display.GetValue()
 261         self.display.Clear()
 262         self.display.SetValue(formula[:-1])
 263         self.display.SetFocus()
 264         
 265 
 266     def OnDivide(self, event):
 267         """
 268         ...    
 269         """
 270         
 271         if self.formula:
 272             return
 273         self.display.AppendText('*')
 274         self.display.SetFocus()
 275         
 276 
 277     def OnMultiply(self, event):
 278         """
 279         ...    
 280         """
 281         
 282         if self.formula:
 283             return
 284         self.display.AppendText('*')
 285         self.display.SetFocus()
 286         
 287 
 288     def OnMinus(self, event):
 289         """
 290         ...    
 291         """
 292         
 293         if self.formula:
 294             return
 295         self.display.AppendText('-')
 296         self.display.SetFocus()
 297         
 298 
 299     def OnPlus(self, event):
 300         """
 301         ...    
 302         """
 303         
 304         if self.formula:
 305             return
 306         self.display.AppendText('+')
 307         self.display.SetFocus()
 308         
 309 
 310     def OnDot(self, event):
 311         """
 312         ...    
 313         """
 314         
 315         if self.formula:
 316             return
 317         self.display.AppendText('.')
 318         self.display.SetFocus()
 319         
 320 
 321     def OnEqual(self, event):
 322         """
 323         ...    
 324         """
 325         
 326         if self.formula:
 327             return
 328         formula = self.display.GetValue()
 329         self.formula = False
 330         try:
 331             self.display.Clear()
 332             output = eval(formula)
 333             self.display.AppendText(str(output))
 334         except StandardError:
 335             self.display.AppendText("Error")
 336             self.display.SetFocus()
 337 
 338     def OnZero(self, event):
 339         """
 340         ...    
 341         """
 342         
 343         if self.formula:
 344             self.display.Clear()
 345             self.formula = False
 346         self.display.AppendText('0')
 347         self.display.SetFocus()
 348         
 349 
 350     def OnOne(self, event):
 351         """
 352         ...    
 353         """
 354         
 355         if self.formula:
 356             self.display.Clear()
 357             self.formula = False
 358         self.display.AppendText('1')
 359         self.display.SetFocus()
 360         
 361 
 362     def OnTwo(self, event):
 363         """
 364         ...    
 365         """
 366         
 367         if self.formula:
 368             self.display.Clear()
 369             self.formula = False
 370         self.display.AppendText('2')
 371         self.display.SetFocus()
 372         
 373 
 374     def OnThree(self, event):
 375         """
 376         ...    
 377         """
 378         
 379         if self.formula:
 380             self.display.Clear()
 381             self.formula = False
 382         self.display.AppendText('3')
 383         self.display.SetFocus()
 384         
 385 
 386     def OnFour(self, event):
 387         """
 388         ...    
 389         """
 390         
 391         if self.formula:
 392             self.display.Clear()
 393             self.formula = False
 394         self.display.AppendText('4')
 395         self.display.SetFocus()
 396         
 397 
 398     def OnFive(self, event):
 399         """
 400         ...    
 401         """
 402         
 403         if self.formula:
 404             self.display.Clear()
 405             self.formula = False
 406         self.display.AppendText('5')
 407         self.display.SetFocus()
 408         
 409 
 410     def OnSix(self, event):
 411         """
 412         ...    
 413         """
 414         
 415         if self.formula:
 416             self.display.Clear()
 417             self.formula = False
 418         self.display.AppendText('6')
 419         self.display.SetFocus()
 420         
 421 
 422     def OnSeven(self, event):
 423         """
 424         ...    
 425         """
 426         
 427         if self.formula:
 428             self.display.Clear()
 429             self.formula = False
 430         self.display.AppendText('7')
 431         self.display.SetFocus()
 432         
 433 
 434     def OnEight(self, event):
 435         """
 436         ...    
 437         """
 438         
 439         if self.formula:
 440             self.display.Clear()
 441             self.formula = False
 442         self.display.AppendText('8')
 443         self.display.SetFocus()
 444         
 445 
 446     def OnNine(self, event):
 447         """
 448         ...    
 449         """
 450         
 451         if self.formula:
 452             self.display.Clear()
 453             self.formula = False
 454         self.display.AppendText('9')
 455         self.display.SetFocus()
 456         
 457 
 458     def OnKeyUp(self, event):
 459         """
 460         Handles the wx.EVT_CHAR_HOOK event for the dialog.
 461         """
 462 
 463         if event.GetKeyCode() == wx.WXK_ESCAPE:
 464             # Close the dialog, no action
 465             self.OnClose(event)
 466 
 467         event.Skip()
 468 
 469         
 470     def OnClose(self, event):
 471         """
 472         ...    
 473         """
 474         
 475         self.Close()
 476 
 477         
 478     def OnCloseWindow(self, event):
 479         """
 480         ...    
 481         """
 482         
 483         self.GetParent().Enable(True)
 484         self.__eventLoop.Exit()
 485         self.Destroy()
 486 
 487 #-------------------------------------------------------------------------------
 488 
 489 class MyFrame(wx.Frame):
 490     def __init__(self):
 491         super(MyFrame, self).__init__(None,
 492                                       -1,
 493                                       title="")
 494 
 495         #------------
 496 
 497         # Simplified init method.
 498         self.SetProperties()
 499         self.CreateCtrls()
 500         self.BindEvents()
 501         self.DoLayout()
 502 
 503         #------------
 504 
 505         self.CenterOnScreen()
 506 
 507     #-----------------------------------------------------------------------
 508 
 509     def SetProperties(self):
 510         """
 511         ...
 512         """
 513 
 514         self.SetTitle("Sample one")
 515         self.SetIcon(wx.Icon('icons/wxwin.ico'))
 516 
 517 
 518     def CreateCtrls(self):
 519         """
 520         ...
 521         """
 522 
 523         self.panel = wx.Panel(self, -1)
 524 
 525         self.btnDlg = wx.Button(self.panel,
 526                                 -1,
 527                                 "&Show customized calculator frame")
 528 
 529         self.btnClose = wx.Button(self.panel,
 530                                   -1,
 531                                   "&Close")
 532 
 533 
 534     def BindEvents(self):
 535         """
 536         Bind some events to an events handler.
 537         """
 538 
 539         # Bind the buttons event to an event handler.
 540         self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
 541 
 542         self.Bind(wx.EVT_BUTTON, self.OnThanksDlg, self.btnDlg)
 543         self.Bind(wx.EVT_BUTTON, self.OnCloseMe, self.btnClose)
 544 
 545 
 546     def DoLayout(self):
 547         """
 548         ...
 549         """
 550 
 551         # mainSizer is the top-level one that manages everything.
 552         mainSizer = wx.BoxSizer(wx.VERTICAL)
 553 
 554         # wx.BoxSizer(window, proportion, flag, border)
 555         # wx.BoxSizer(sizer, proportion, flag, border)
 556         mainSizer.Add(self.btnDlg, 1, wx.EXPAND | wx.ALL, 10)
 557         mainSizer.Add(self.btnClose, 1, wx.EXPAND | wx.ALL, 10)
 558 
 559         # Finally, tell the panel to use the sizer for layout.
 560         self.panel.SetAutoLayout(True)
 561         self.panel.SetSizer(mainSizer)
 562 
 563         mainSizer.Fit(self.panel)
 564 
 565 
 566     def OnCloseMe(self, event):
 567         """
 568         ...
 569         """
 570 
 571         self.Close(True)
 572 
 573 
 574     def OnThanksDlg(self, event):
 575         """
 576         ...
 577         """
 578 
 579         frame = MyCalculator(self, -1, 'Calculator')
 580         
 581 
 582     def OnCloseWindow(self, event):
 583         """
 584         ...
 585         """
 586 
 587         self.Destroy()
 588 
 589 #-------------------------------------------------------------------------------
 590 
 591 class MyApp(wx.App):
 592     """
 593     ...
 594     """
 595     def OnInit(self):
 596 
 597         #------------
 598 
 599         frame = MyFrame()
 600         self.SetTopWindow(frame)
 601         frame.Show(True)
 602 
 603         return True
 604 
 605 #---------------------------------------------------------------------------
 606 
 607 def main():
 608     app = MyApp(False)
 609     app.MainLoop()
 610 
 611 #---------------------------------------------------------------------------
 612 
 613 if __name__ == "__main__" :
 614     main()


Sample two

img_sample_two.png

   1 # sample_two.py
   2 
   3 """
   4 
   5 Purpose  : Create a customized calculator
   6 Author   : Jan Bodnar (zetcode.com)
   7          : Modified By Ecco - May 2021
   8 Thank to : Daniel Ramos (custom_button)
   9 Link     : https://zetcode.com/wxpython/layout/
  10 
  11 """
  12 
  13 import os
  14 import sys
  15 import wx
  16 from   custom_button import CustomButton as CustomBtn
  17 
  18 # class MyCalculator
  19 # class MyFrame
  20 
  21 #-------------------------------------------------------------------------------
  22 
  23 class MyCalculator(wx.Frame):
  24     def __init__(self, parent, id, title):
  25         wx.Frame.__init__(self, parent,
  26                           -1, title,
  27                           style=wx.DEFAULT_FRAME_STYLE)
  28 
  29         #------------
  30        
  31         if wx.Platform == "__WXMSW__":
  32             self.SetDoubleBuffered(True)
  33         
  34         #------------
  35             
  36         self.parent = parent
  37         self.formula = False
  38         
  39         #------------
  40 
  41         # Return icons folder.
  42         self.icon_dir = wx.GetApp().GetIconDir()
  43         # Return bitmaps folder. 
  44         self.bitmap_dir = wx.GetApp().GetBitmapDir()
  45         
  46         #------------
  47         
  48         # Simplified init method
  49         self.SetProperties()
  50         self.CreateCtrls()
  51         self.MakeMenuBar()
  52         self.BindEvents()
  53         self.DoLayout()        
  54 
  55         #------------
  56 
  57         self.CenterOnParent()
  58         self.GetParent().Enable(False)
  59         self.Show(True)
  60 
  61         self.__eventLoop = wx.GUIEventLoop()
  62         self.__eventLoop.Run()
  63         
  64     #---------------------------------------------------------------------------
  65 
  66     def SetProperties(self):
  67         """
  68         Set the dialog properties (title, icon...).
  69         """
  70 
  71         # Set frame icon. 
  72         frameicon = wx.Icon(os.path.join(self.icon_dir,
  73                                          "wxwin.ico"),
  74                             type=wx.BITMAP_TYPE_ICO)
  75 
  76         self.SetIcon(frameicon)
  77         self.SetSize((420, 300))
  78         self.SetMinSize((430, 310))
  79         
  80 
  81     def MakeMenuBar(self):
  82         """
  83         Make menu data.
  84         """
  85 
  86         menubar = wx.MenuBar()
  87 
  88         #------------
  89         
  90         menuFile = wx.Menu()
  91 
  92         #------------
  93 
  94         # Add a bitmap to "exitItem" menu.
  95         bmp = wx.Bitmap(os.path.join(self.bitmap_dir,
  96                                      "item_quit.png"),
  97                         type=wx.BITMAP_TYPE_PNG)     
  98 
  99         exitItem = wx.MenuItem(parentMenu=menuFile, 
 100                                id=22,
 101                                text="&Quit\tCtrl+Q",
 102                                helpString="Exit Calculator.",
 103                                kind=wx.ITEM_NORMAL,
 104                                subMenu=None)
 105         exitItem.SetBitmap(bmp)
 106         menuFile.Append(exitItem)
 107         
 108         #------------
 109         
 110         menubar.Append(menuFile, '&File')
 111 
 112         #------------
 113         
 114         self.SetMenuBar(menubar)
 115 
 116         
 117     def CreateCtrls(self):
 118         """
 119         ...    
 120         """
 121         
 122         self.panel = wx.Panel(self, -1)
 123 
 124         #------------
 125         
 126         self.display = wx.TextCtrl(self.panel, -1,
 127                                    "",
 128                                    style=wx.TE_RIGHT|
 129                                          wx.TE_PROCESS_ENTER)
 130         self.display.SetBackgroundColour("#fded68") 
 131         self.display.SetForegroundColour("#0326f9") 
 132         self.display.SetFocus()
 133         
 134         #------------
 135         
 136         self.btn1 = CustomBtn(self.panel, 20, 'Clr')
 137         self.btn1.set_font(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
 138         self.btn1.set_foreground_color('#008B00')
 139         self.btn1.set_text_shadow((1, 1, '#ffffff'))
 140         self.btn1.set_bg_gradient(('#CEE3F2', '#438FC9'), ('#ABCEE9', '#3279AD'))
 141         self.btn1.set_border((1, '#3076A9', 3))
 142         self.btn1.set_padding((5, 10, 5, 10))
 143         self.btn1.center_content(True)
 144         
 145         self.btn2 = CustomBtn(self.panel, 21, 'Bck')
 146         self.btn2.set_font(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
 147         self.btn2.set_foreground_color('#0e4e0e')
 148         self.btn2.set_text_shadow((1, 1, '#ffffff'))
 149         self.btn2.set_bg_gradient(('#CEE3F2', '#438FC9'), ('#ABCEE9', '#3279AD'))
 150         self.btn2.set_border((1, '#3076A9', 3))
 151         self.btn2.set_padding((5, 10, 5, 10))
 152         self.btn2.center_content(True)
 153 
 154         self.txt3 = wx.StaticText(self.panel, -1, '')
 155 
 156         self.btn4 = CustomBtn(self.panel, 22, 'Close')
 157         self.btn4.set_font(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
 158         self.btn4.set_foreground_color('red')
 159         self.btn4.set_text_shadow((1, 1, '#ffffff'))
 160         self.btn4.set_bg_gradient(('#CEE3F2', '#438FC9'), ('#ABCEE9', '#3279AD'))
 161         self.btn4.set_border((1, '#3076A9', 3))
 162         self.btn4.set_padding((5, 10, 5, 10))
 163         self.btn4.center_content(True)
 164 
 165         self.btn5 = CustomBtn(self.panel, 1, '7')
 166         self.btn5.set_foreground_color('#000000')
 167         self.btn5.set_text_shadow((1, 1, '#ffffff'))
 168         self.btn5.set_bg_gradient(('#CEE3F2', '#438FC9'), ('#ABCEE9', '#3279AD'))
 169         self.btn5.set_border((1, '#3076A9', 3))
 170         self.btn5.set_padding((5, 10, 5, 10))
 171         self.btn5.center_content(True)
 172 
 173         self.btn6 = CustomBtn(self.panel, 2, '8')
 174         self.btn6.set_foreground_color('#000000')
 175         self.btn6.set_text_shadow((1, 1, '#ffffff'))
 176         self.btn6.set_bg_gradient(('#CEE3F2', '#438FC9'), ('#ABCEE9', '#3279AD'))
 177         self.btn6.set_border((1, '#3076A9', 3))
 178         self.btn6.set_padding((5, 10, 5, 10))
 179         self.btn6.center_content(True)
 180 
 181         self.btn7 = CustomBtn(self.panel, 3, '9')
 182         self.btn7.set_foreground_color('#000000')
 183         self.btn7.set_text_shadow((1, 1, '#ffffff'))
 184         self.btn7.set_bg_gradient(('#CEE3F2', '#438FC9'), ('#ABCEE9', '#3279AD'))
 185         self.btn7.set_border((1, '#3076A9', 3))
 186         self.btn7.set_padding((5, 10, 5, 10))
 187         self.btn7.center_content(True)
 188         
 189         self.btn8 = CustomBtn(self.panel, 4, '/')
 190         self.btn8.set_foreground_color('#000000')
 191         self.btn8.set_text_shadow((1, 1, '#ffffff'))
 192         self.btn8.set_bg_gradient(('#CEE3F2', '#438FC9'), ('#ABCEE9', '#3279AD'))
 193         self.btn8.set_border((1, '#3076A9', 3))
 194         self.btn8.set_padding((5, 10, 5, 10))
 195         self.btn8.center_content(True)
 196         
 197         self.btn9 = CustomBtn(self.panel, 5, '4')
 198         self.btn9.set_foreground_color('#000000')
 199         self.btn9.set_text_shadow((1, 1, '#ffffff'))
 200         self.btn9.set_bg_gradient(('#CEE3F2', '#438FC9'), ('#ABCEE9', '#3279AD'))
 201         self.btn9.set_border((1, '#3076A9', 3))
 202         self.btn9.set_padding((5, 10, 5, 10))
 203         self.btn9.center_content(True)
 204         
 205         self.btn10 = CustomBtn(self.panel, 6, '5')
 206         self.btn10.set_foreground_color('#000000')
 207         self.btn10.set_text_shadow((1, 1, '#ffffff'))
 208         self.btn10.set_bg_gradient(('#CEE3F2', '#438FC9'), ('#ABCEE9', '#3279AD'))
 209         self.btn10.set_border((1, '#3076A9', 3))
 210         self.btn10.set_padding((5, 10, 5, 10))
 211         self.btn10.center_content(True)
 212         
 213         self.btn11 = CustomBtn(self.panel, 7, '6')
 214         self.btn11.set_foreground_color('#000000')
 215         self.btn11.set_text_shadow((1, 1, '#ffffff'))
 216         self.btn11.set_bg_gradient(('#CEE3F2', '#438FC9'), ('#ABCEE9', '#3279AD'))
 217         self.btn11.set_border((1, '#3076A9', 3))
 218         self.btn11.set_padding((5, 10, 5, 10))
 219         self.btn11.center_content(True)
 220         
 221         self.btn12 = CustomBtn(self.panel, 8, '*')
 222         self.btn12.set_foreground_color('#000000')
 223         self.btn12.set_text_shadow((1, 1, '#ffffff'))
 224         self.btn12.set_bg_gradient(('#CEE3F2', '#438FC9'), ('#ABCEE9', '#3279AD'))
 225         self.btn12.set_border((1, '#3076A9', 3))
 226         self.btn12.set_padding((5, 10, 5, 10))
 227         self.btn12.center_content(True)
 228         
 229         self.btn13 = CustomBtn(self.panel, 9, '1')
 230         self.btn13.set_foreground_color('#000000')
 231         self.btn13.set_text_shadow((1, 1, '#ffffff'))
 232         self.btn13.set_bg_gradient(('#CEE3F2', '#438FC9'), ('#ABCEE9', '#3279AD'))
 233         self.btn13.set_border((1, '#3076A9', 3))
 234         self.btn13.set_padding((5, 10, 5, 10))
 235         self.btn13.center_content(True)
 236         
 237         self.btn14 = CustomBtn(self.panel, 10, '2')
 238         self.btn14.set_foreground_color('#000000')
 239         self.btn14.set_text_shadow((1, 1, '#ffffff'))
 240         self.btn14.set_bg_gradient(('#CEE3F2', '#438FC9'), ('#ABCEE9', '#3279AD'))
 241         self.btn14.set_border((1, '#3076A9', 3))
 242         self.btn14.set_padding((5, 10, 5, 10))
 243         self.btn14.center_content(True)
 244         
 245         self.btn15 = CustomBtn(self.panel, 11, '3')
 246         self.btn15.set_foreground_color('#000000')
 247         self.btn15.set_text_shadow((1, 1, '#ffffff'))
 248         self.btn15.set_bg_gradient(('#CEE3F2', '#438FC9'), ('#ABCEE9', '#3279AD'))
 249         self.btn15.set_border((1, '#3076A9', 3))
 250         self.btn15.set_padding((5, 10, 5, 10))
 251         self.btn15.center_content(True)
 252         
 253         self.btn16 = CustomBtn(self.panel, 12, '-')
 254         self.btn16.set_foreground_color('#000000')
 255         self.btn16.set_text_shadow((1, 1, '#ffffff'))
 256         self.btn16.set_bg_gradient(('#CEE3F2', '#438FC9'), ('#ABCEE9', '#3279AD'))
 257         self.btn16.set_border((1, '#3076A9', 3))
 258         self.btn16.set_padding((5, 10, 5, 10))
 259         self.btn16.center_content(True)
 260         
 261         self.btn17 = CustomBtn(self.panel, 13, '0')
 262         self.btn17.set_foreground_color('#000000')
 263         self.btn17.set_text_shadow((1, 1, '#ffffff'))
 264         self.btn17.set_bg_gradient(('#CEE3F2', '#438FC9'), ('#ABCEE9', '#3279AD'))
 265         self.btn17.set_border((1, '#3076A9', 3))
 266         self.btn17.set_padding((5, 10, 5, 10))
 267         self.btn17.center_content(True)
 268 
 269         self.btn18 = CustomBtn(self.panel, 14, '.')
 270         self.btn18.set_foreground_color('#000000')
 271         self.btn18.set_text_shadow((1, 1, '#ffffff'))
 272         self.btn18.set_bg_gradient(('#CEE3F2', '#438FC9'), ('#ABCEE9', '#3279AD'))
 273         self.btn18.set_border((1, '#3076A9', 3))
 274         self.btn18.set_padding((5, 10, 5, 10))
 275         self.btn18.center_content(True)
 276         
 277         self.btn19 = CustomBtn(self.panel, 15, '=')
 278         self.btn19.set_foreground_color('#000000')
 279         self.btn19.set_text_shadow((1, 1, '#ffffff'))
 280         self.btn19.set_bg_gradient(('#CEE3F2', '#438FC9'), ('#ABCEE9', '#3279AD'))
 281         self.btn19.set_border((1, '#3076A9', 3))
 282         self.btn19.set_padding((5, 10, 5, 10))
 283         self.btn19.center_content(True)
 284         
 285         self.btn20 = CustomBtn(self.panel, 16, '+')
 286         self.btn20.set_foreground_color('#000000')
 287         self.btn20.set_text_shadow((1, 1, '#ffffff'))
 288         self.btn20.set_bg_gradient(('#CEE3F2', '#438FC9'), ('#ABCEE9', '#3279AD'))
 289         self.btn20.set_border((1, '#3076A9', 3))
 290         self.btn20.set_padding((5, 10, 5, 10))
 291         self.btn20.center_content(True)
 292 
 293         self.panel.SetBackgroundColour("#cce8f2")        
 294         
 295 
 296     def BindEvents(self):
 297         """
 298         ...  
 299         """
 300 
 301         self.display.Bind(wx.EVT_TEXT_ENTER, self.OnTextEnter)
 302         
 303         self.Bind(wx.EVT_BUTTON, self.OnClear, id=20)
 304         self.Bind(wx.EVT_BUTTON, self.OnBackspace, id=21)
 305         self.Bind(wx.EVT_BUTTON, self.OnClose, id=22)
 306         self.Bind(wx.EVT_BUTTON, self.OnSeven, id=1)
 307         self.Bind(wx.EVT_BUTTON, self.OnEight, id=2)
 308         self.Bind(wx.EVT_BUTTON, self.OnNine, id=3)
 309         self.Bind(wx.EVT_BUTTON, self.OnDivide, id=4)
 310         self.Bind(wx.EVT_BUTTON, self.OnFour, id=5)
 311         self.Bind(wx.EVT_BUTTON, self.OnFive, id=6)
 312         self.Bind(wx.EVT_BUTTON, self.OnSix, id=7)
 313         self.Bind(wx.EVT_BUTTON, self.OnMultiply, id=8)
 314         self.Bind(wx.EVT_BUTTON, self.OnOne, id=9)
 315         self.Bind(wx.EVT_BUTTON, self.OnTwo, id=10)
 316         self.Bind(wx.EVT_BUTTON, self.OnThree, id=11)
 317         self.Bind(wx.EVT_BUTTON, self.OnMinus, id=12)
 318         self.Bind(wx.EVT_BUTTON, self.OnZero, id=13)
 319         self.Bind(wx.EVT_BUTTON, self.OnDot, id=14)
 320         self.Bind(wx.EVT_BUTTON, self.OnEqual, id=15)
 321         self.Bind(wx.EVT_BUTTON, self.OnPlus, id=16)
 322 
 323         self.Bind(wx.EVT_MENU, self.OnClose, id=22)
 324 
 325         self.Bind(wx.EVT_CHAR_HOOK, self.OnKeyUp)
 326         
 327         # (Allows frame's title-bar close to work)
 328         self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) 
 329         
 330 
 331     def DoLayout(self):
 332         """
 333         ...    
 334         """
 335 
 336         # Sizers         
 337         # MainSizer is the top-level one that manages everything   
 338         mainSizer = wx.BoxSizer(wx.VERTICAL)
 339         gridSizer = wx.GridSizer(5, 4, 5, 5)
 340 
 341         #------------
 342 
 343         # Assign widgets to sizers 
 344         mainSizer.Add(self.display, 0, wx.EXPAND | wx.ALL, 5)
 345 
 346         gridSizer.AddMany([(self.btn1, 1, wx.EXPAND),
 347                            (self.btn2, 1, wx.EXPAND),
 348                            (self.txt3, 1, wx.EXPAND),
 349                            (self.btn4, 1, wx.EXPAND),
 350                            (self.btn5, 1, wx.EXPAND),
 351                            (self.btn6, 1, wx.EXPAND),
 352                            (self.btn7, 1, wx.EXPAND),
 353                            (self.btn8, 1, wx.EXPAND),
 354                            (self.btn9, 1, wx.EXPAND),
 355                            (self.btn10, 1, wx.EXPAND),
 356                            (self.btn11, 1, wx.EXPAND),
 357                            (self.btn12, 1, wx.EXPAND),
 358                            (self.btn13, 1, wx.EXPAND),
 359                            (self.btn14, 1, wx.EXPAND),
 360                            (self.btn15, 1, wx.EXPAND),
 361                            (self.btn16, 1, wx.EXPAND),
 362                            (self.btn17, 1, wx.EXPAND),
 363                            (self.btn18, 1, wx.EXPAND),
 364                            (self.btn19, 1, wx.EXPAND),
 365                            (self.btn20, 1, wx.EXPAND)])
 366 
 367         # Assign to mainSizer the other sizers
 368         mainSizer.Add(gridSizer, 1, wx.EXPAND | wx.ALL, 5)
 369 
 370         #------------
 371         
 372         self.panel.SetSizer(mainSizer)
 373         mainSizer.Fit(self)
 374         
 375 
 376     def OnTextEnter(self, event):
 377         """
 378         ...    
 379         """
 380 
 381         self.OnEqual(event)
 382         
 383 
 384     def OnClear(self, event):
 385         """
 386         ...    
 387         """
 388                 
 389         self.display.Clear()
 390         self.display.SetFocus()
 391         
 392 
 393     def OnBackspace(self, event):
 394         """
 395         ...    
 396         """
 397         
 398         formula = self.display.GetValue()
 399         self.display.Clear()
 400         self.display.SetValue(formula[:-1])
 401         self.display.SetFocus()
 402         
 403 
 404     def OnDivide(self, event):
 405         """
 406         ...    
 407         """
 408         
 409         if self.formula:
 410             return
 411         self.display.AppendText('*')
 412         self.display.SetFocus()
 413         
 414 
 415     def OnMultiply(self, event):
 416         """
 417         ...    
 418         """
 419         
 420         if self.formula:
 421             return
 422         self.display.AppendText('*')
 423         self.display.SetFocus()
 424         
 425 
 426     def OnMinus(self, event):
 427         """
 428         ...    
 429         """
 430         
 431         if self.formula:
 432             return
 433         self.display.AppendText('-')
 434         self.display.SetFocus()
 435         
 436 
 437     def OnPlus(self, event):
 438         """
 439         ...    
 440         """
 441         
 442         if self.formula:
 443             return
 444         self.display.AppendText('+')
 445         self.display.SetFocus()
 446         
 447 
 448     def OnDot(self, event):
 449         """
 450         ...    
 451         """
 452         
 453         if self.formula:
 454             return
 455         self.display.AppendText('.')
 456         self.display.SetFocus()
 457         
 458 
 459     def OnEqual(self, event):
 460         """
 461         ...    
 462         """
 463         
 464         if self.formula:
 465             return
 466         formula = self.display.GetValue()
 467         self.formula = False
 468 
 469         self.display.Clear()
 470         output = eval(formula)
 471         self.display.AppendText(str(output))
 472         self.display.SetFocus()
 473 
 474 
 475     def OnZero(self, event):
 476         """
 477         ...    
 478         """
 479         
 480         if self.formula:
 481             self.display.Clear()
 482             self.formula = False
 483         self.display.AppendText('0')
 484         self.display.SetFocus()
 485         
 486 
 487     def OnOne(self, event):
 488         """
 489         ...    
 490         """
 491         
 492         if self.formula:
 493             self.display.Clear()
 494             self.formula = False
 495         self.display.AppendText('1')
 496         self.display.SetFocus()
 497         
 498 
 499     def OnTwo(self, event):
 500         """
 501         ...    
 502         """
 503         
 504         if self.formula:
 505             self.display.Clear()
 506             self.formula = False
 507         self.display.AppendText('2')
 508         self.display.SetFocus()
 509         
 510 
 511     def OnThree(self, event):
 512         """
 513         ...    
 514         """
 515         
 516         if self.formula:
 517             self.display.Clear()
 518             self.formula = False
 519         self.display.AppendText('3')
 520         self.display.SetFocus()
 521         
 522 
 523     def OnFour(self, event):
 524         """
 525         ...    
 526         """
 527         
 528         if self.formula:
 529             self.display.Clear()
 530             self.formula = False
 531         self.display.AppendText('4')
 532         self.display.SetFocus()
 533         
 534 
 535     def OnFive(self, event):
 536         """
 537         ...    
 538         """
 539         
 540         if self.formula:
 541             self.display.Clear()
 542             self.formula = False
 543         self.display.AppendText('5')
 544         self.display.SetFocus()
 545         
 546 
 547     def OnSix(self, event):
 548         """
 549         ...    
 550         """
 551         
 552         if self.formula:
 553             self.display.Clear()
 554             self.formula = False
 555         self.display.AppendText('6')
 556         self.display.SetFocus()
 557         
 558 
 559     def OnSeven(self, event):
 560         """
 561         ...    
 562         """
 563         
 564         if self.formula:
 565             self.display.Clear()
 566             self.formula = False
 567         self.display.AppendText('7')
 568         self.display.SetFocus()
 569         
 570 
 571     def OnEight(self, event):
 572         """
 573         ...    
 574         """
 575         
 576         if self.formula:
 577             self.display.Clear()
 578             self.formula = False
 579         self.display.AppendText('8')
 580         self.display.SetFocus()
 581         
 582 
 583     def OnNine(self, event):
 584         """
 585         ...    
 586         """
 587         
 588         if self.formula:
 589             self.display.Clear()
 590             self.formula = False
 591         self.display.AppendText('9')
 592         self.display.SetFocus()
 593         
 594 
 595     def OnKeyUp(self, event):
 596         """
 597         Handles the wx.EVT_CHAR_HOOK event for the dialog.
 598         """
 599 
 600         if event.GetKeyCode() == wx.WXK_ESCAPE:
 601             # Close the dialog, no action
 602             self.OnClose(event)
 603 
 604         event.Skip()
 605 
 606         
 607     def OnClose(self, event):
 608         """
 609         ...    
 610         """
 611         
 612         self.Close()
 613 
 614         
 615     def OnCloseWindow(self, event):
 616         """
 617         ...    
 618         """
 619         
 620         self.GetParent().Enable(True)
 621         self.__eventLoop.Exit()
 622         self.Destroy()
 623         
 624 #-------------------------------------------------------------------------------
 625 
 626 class MyFrame(wx.Frame):
 627     def __init__(self):
 628         super(MyFrame, self).__init__(None,
 629                                       -1,
 630                                       title="")
 631 
 632         #------------
 633 
 634         # Simplified init method.
 635         self.SetProperties()
 636         self.CreateCtrls()
 637         self.BindEvents()
 638         self.DoLayout()
 639 
 640         #------------
 641 
 642         self.CenterOnScreen()
 643 
 644     #-----------------------------------------------------------------------
 645 
 646     def SetProperties(self):
 647         """
 648         ...
 649         """
 650 
 651         self.SetTitle("Sample one")
 652         self.SetIcon(wx.Icon('icon/wxwin.ico'))
 653 
 654 
 655     def CreateCtrls(self):
 656         """
 657         ...
 658         """
 659 
 660         self.panel = wx.Panel(self, -1)
 661 
 662         self.btnDlg = wx.Button(self.panel,
 663                                 -1,
 664                                 "&Show customized calculator frame")
 665 
 666         self.btnClose = wx.Button(self.panel,
 667                                   -1,
 668                                   "&Close")
 669 
 670 
 671     def BindEvents(self):
 672         """
 673         Bind some events to an events handler.
 674         """
 675 
 676         # Bind the close event to an event handler.
 677         self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
 678 
 679         # Bind the buttons event to an event handler.
 680         self.Bind(wx.EVT_BUTTON, self.OnScreenshot, self.btnDlg)
 681         self.Bind(wx.EVT_BUTTON, self.OnCloseMe, self.btnClose)
 682 
 683 
 684     def DoLayout(self):
 685         """
 686         ...
 687         """
 688 
 689         # mainSizer is the top-level one that manages everything.
 690         mainSizer = wx.BoxSizer(wx.VERTICAL)
 691 
 692         # wx.BoxSizer(window, proportion, flag, border)
 693         # wx.BoxSizer(sizer, proportion, flag, border)
 694         mainSizer.Add(self.btnDlg, 1, wx.EXPAND | wx.ALL, 10)
 695         mainSizer.Add(self.btnClose, 1, wx.EXPAND | wx.ALL, 10)
 696 
 697         # Finally, tell the panel to use the sizer for layout.
 698         self.panel.SetAutoLayout(True)
 699         self.panel.SetSizer(mainSizer)
 700 
 701         mainSizer.Fit(self.panel)
 702 
 703 
 704     def OnCloseMe(self, event):
 705         """
 706         ...
 707         """
 708 
 709         self.Close(True)
 710 
 711 
 712     def OnScreenshot(self, event):
 713         """
 714         ...
 715         """
 716 
 717         frmCal = MyCalculator(self, -1, 'Calculator')
 718         
 719 
 720     def OnCloseWindow(self, event):
 721         """
 722         ...
 723         """
 724 
 725         self.Destroy()
 726 
 727 #-------------------------------------------------------------------------------
 728 
 729 class MyApp(wx.App):
 730     def OnInit(self):
 731 
 732         #------------
 733         
 734         self.installDir = os.path.split(os.path.abspath(sys.argv[0]))[0]
 735 
 736         #------------
 737         
 738         frame = MyFrame()
 739         self.SetTopWindow(frame)
 740         frame.Show(True)
 741 
 742         return True
 743 
 744     #-----------------------------------------------------------------------
 745     
 746     def GetInstallDir(self):
 747         """
 748         Return the installation directory for my application.
 749         """
 750 
 751         return self.installDir
 752 
 753 
 754     def GetIconDir(self):
 755         """
 756         Return the icons directory for my application.
 757         """
 758 
 759         icon_dir = os.path.join(self.installDir, "icon")
 760         return icon_dir
 761 
 762 
 763     def GetBitmapDir(self):
 764         """
 765         Return the bitmaps directory for my application.
 766         """
 767 
 768         bitmap_dir = os.path.join(self.installDir, "bitmap")
 769         return bitmap_dir
 770     
 771 #---------------------------------------------------------------------------
 772 
 773 def main():
 774     app = MyApp(False)
 775     app.MainLoop()
 776 
 777 #---------------------------------------------------------------------------
 778 
 779 if __name__ == "__main__" :
 780     main()


Sample three

img_sample_three.png

   1 # sample_three.py
   2 
   3 """
   4 
   5 https://vcansimplify.wordpress.com/category/python-2/wxpython-python/
   6 
   7 """
   8 
   9 import wx 
  10 from math import *  # To enable writing sin(13) instead of math.sin(13)
  11 
  12 # class MyFrame
  13 # class MyCalcFrame
  14 # class MyApp
  15 
  16 #---------------------------------------------------------------------------
  17 
  18 class MyFrame(wx.Frame):
  19     """
  20     Frame and widgets to handle input and output of mortgage calc.
  21     """
  22     def __init__(self, parent):
  23         wx.Frame.__init__(self, parent, -1, "Math.sin calculator")
  24 
  25         self.SetIcon(wx.Icon('./icons/wxwin.ico', wx.BITMAP_TYPE_ICO))
  26 
  27         #------------
  28         
  29         # Add panel, labels, text and sizer widgets.
  30         panel = wx.Panel(self, -1)
  31 
  32         self.text = wx.TextCtrl(panel, -1,
  33                                 size=(290, 100),
  34                                 style=wx.TE_MULTILINE)
  35         
  36         solveBtn = wx.Button(panel, -1, "&Solve")
  37         solveBtn.Bind(wx.EVT_BUTTON, self.solveFunc)
  38 
  39         clearBtn = wx.Button(panel, -1, "&Clear")
  40         clearBtn.Bind(wx.EVT_BUTTON, self.clearFunc)
  41             
  42         # Use boxsizer to add border around sizer.
  43         border = wx.BoxSizer(wx.VERTICAL)
  44         border.Add(self.text, 1, wx.EXPAND | wx.ALL, 5)
  45         border.Add(solveBtn, 1, wx.EXPAND | wx.ALL, 5)
  46         border.Add(clearBtn, 1, wx.EXPAND | wx.ALL, 5)
  47         
  48         panel.SetSizerAndFit(border)
  49         self.Fit()
  50 
  51     #-----------------------------------------------------------------------
  52         
  53     def solveFunc(self, event):
  54         """
  55         What to when 'Solve' is clicked
  56         wx calls this function with and 'event' object.
  57         """
  58 
  59         try:
  60             # Evaluate the string in 'text' and put the answer back.
  61             ans = eval(self.text.GetValue())
  62             self.text.SetValue(str(ans))
  63         except Exception:
  64             print('error')
  65 
  66 
  67     def clearFunc(self,event):
  68         """
  69         Put a blank string in text when 'Clear' is clicked.
  70         """
  71         
  72         self.text.SetValue(str(''))
  73 
  74 #---------------------------------------------------------------------------
  75         
  76 class MyCalcFrame(MyFrame):
  77     """
  78     Constructor.
  79     Inherit from the MainFrame created in wxFowmBuilder and create CalcFrame.
  80     """
  81     def __init__(self, parent):
  82         # Initialize parent class.
  83         MyFrame.__init__(self, parent)
  84         
  85 #---------------------------------------------------------------------------
  86 
  87 class MyApp(wx.App):    
  88     def OnInit(self):
  89 
  90         #------------
  91 
  92         # Create an object of MyCalcFrame.
  93         frame = MyCalcFrame(None)
  94         self.SetTopWindow(frame)
  95         # Show the frame.
  96         frame.Show(True)
  97 
  98         return True
  99     
 100 #---------------------------------------------------------------------------
 101 
 102 def main():
 103     # Mandatory in wx, create an app, False stands for not 
 104     # deteriction stdin/stdout refer manual for details.
 105     app = MyApp(False)
 106     # Start the applications.
 107     app.MainLoop()
 108 
 109 #---------------------------------------------------------------------------
 110 
 111 if __name__ == "__main__" :
 112     main()


Sample four

img_sample_four.png

   1 # sample_four.py
   2 
   3 """
   4 
   5 Author :  BridgeGuy
   6 Beta Version
   7 Uses Reverse Polish Notation similar to HP calculators
   8 Stores up to 4 values in the stack
   9 Base units is feet.
  10 Can convert from decimal feet to imperial units (ft-in)
  11 Conversion to imperial units is to nearest 1/8"
  12 Can convert to inches
  13 Will accept any decimal input
  14 Imperial units input must be in the form of #'# #,# (5'3 1,2) ==> 5'-3 1/2"
  15 There is only a space between the inches numeral and numerator of the inch fraction.
  16 
  17 https://github.com/BridgeGuy/wxCalculator
  18 
  19 """
  20 
  21 import wx
  22 import math
  23 from fractions import Fraction
  24 
  25 DISP_COLOR = wx.Colour(243, 248, 205) # Yellowish
  26 STACK4 = 0
  27 STACK3 = 0
  28 STACK2 = 0
  29 STACK1 = 0
  30 
  31 # class MainFrame
  32 # class CalcPanel
  33 
  34 #---------------------------------------------------------------------------
  35 
  36 class MainFrame(wx.Frame):
  37     """
  38     Main calculator frame
  39     """
  40     def __init__(self, *args, **kwargs):
  41         kwargs.setdefault('title', "Feet-Inch calculator")
  42         wx.Frame.__init__(self, *args, **kwargs)
  43 
  44         self.SetIcon(wx.Icon('./icons/wxwin.ico', wx.BITMAP_TYPE_ICO))
  45 
  46         #------------
  47         
  48         self.calcPanel = CalcPanel(self)
  49         fsizer = wx.BoxSizer(wx.VERTICAL)
  50         fsizer.Add(self.calcPanel, 1, wx.EXPAND, 10)
  51         self.CenterOnScreen()
  52         self.SetSizerAndFit(fsizer)
  53 
  54 #---------------------------------------------------------------------------
  55         
  56 class CalcPanel(wx.Panel):
  57     """
  58     Panel containing display, conversion radiobox and buttons
  59     """
  60     def __init__(self, *args, **kwargs):
  61         wx.Panel.__init__(self, *args, **kwargs)
  62         
  63         sizer = wx.GridBagSizer(3,2)
  64 
  65         #------------- Display ------------------
  66         self.display4 = wx.StaticText(self, -1, str(STACK4),
  67                                       style=wx.ALIGN_RIGHT|wx.ST_NO_AUTORESIZE)
  68         self.display3 = wx.StaticText(self, -1, str(STACK3), 
  69                                       style=wx.ALIGN_RIGHT|wx.ST_NO_AUTORESIZE)
  70         self.display2 = wx.StaticText(self, -1, str(STACK2),
  71                                       style=wx.ALIGN_RIGHT|wx.ST_NO_AUTORESIZE)
  72         self.display1 = wx.StaticText(self, -1, str(STACK1),
  73                                       style=wx.ALIGN_RIGHT|wx.ST_NO_AUTORESIZE)
  74         self.display = wx.TextCtrl(self, -1, style=wx.TE_RIGHT|wx.WANTS_CHARS)
  75         self.display.Bind(wx.EVT_KEY_DOWN, self.OnKeyPress)
  76         self.text4 = wx.StaticText(self, -1, "4:")
  77         self.text3 = wx.StaticText(self, -1, "3:")
  78         self.text2 = wx.StaticText(self, -1, "2:")
  79         self.text1 = wx.StaticText(self, -1, "1:")
  80         sizer.Add(self.text4, (0,0), (1,1), wx.EXPAND|wx.LEFT|wx.TOP, 10)
  81         sizer.Add(self.text3, (1,0), (1,1), wx.EXPAND|wx.LEFT, 10)
  82         sizer.Add(self.text2, (2,0), (1,1), wx.EXPAND|wx.LEFT, 10)
  83         sizer.Add(self.text1, (3,0), (1,1), wx.EXPAND|wx.LEFT, 10)
  84         sizer.Add(self.display4, (0,1), (1,1), wx.EXPAND|wx.RIGHT|wx.TOP, 10)
  85         sizer.Add(self.display3, (1,1), (1,1), wx.EXPAND|wx.RIGHT, 10)
  86         sizer.Add(self.display2, (2,1), (1,1), wx.EXPAND|wx.RIGHT, 10)
  87         sizer.Add(self.display1, (3,1), (1,1), wx.EXPAND|wx.RIGHT, 10)
  88         sizer.Add(self.display, (4,0), (1,2), wx.EXPAND|wx.RIGHT|wx.LEFT, 10)
  89 
  90         #------------- Conversion RadioBox --------------
  91         self.rbox = wx.RadioBox(self, label= "Conversion",
  92                            choices=["Feet", "Inches", "Decimal"],
  93                            majorDimension=3, style=wx.RA_SPECIFY_COLS)
  94         self.rbox.SetSelection(0)
  95         sizer.Add(self.rbox, (5,0), (1,2), wx.ALIGN_LEFT|wx.EXPAND|wx.RIGHT|wx.LEFT, 10)
  96         self.rbox.Bind(wx.EVT_RADIOBOX, self.conversion)
  97 
  98         #-------------- Buttons -----------------
  99         gsizer1 = wx.GridSizer(5,3,2,2)
 100         buttons1 = (('7', '8', '9'),
 101                     ('4', '5', '6'),
 102                     ('3', '2', '1'),
 103                     ('C', '0', '.'))
 104         gsizer2 = wx.GridSizer(5,2,2,2)
 105         buttons2 = (("Swap", "Del"),
 106                     ("/", "'"),
 107                     ("*", "^"),
 108                     ("-", "sqrt"),
 109                     ("+", "Enter"))
 110         gsizer1.Add((1,1), 1, wx.EXPAND)
 111         gsizer1.Add((1,1), 1, wx.EXPAND)
 112         gsizer1.Add((1,1), 1, wx.EXPAND)
 113         for row in buttons1:
 114             for label in row:
 115                 b = wx.Button(self, label=label, size=(40,-1))
 116                 gsizer1.Add(b)
 117                 b.Bind(wx.EVT_BUTTON, self.OnButton)                
 118         sizer.Add(gsizer1, (6,0),(1,1), wx.EXPAND|wx.LEFT|wx.BOTTOM|wx.ALIGN_BOTTOM, 10)
 119 
 120         for row in buttons2:
 121             for label in row:
 122                 b = wx.Button(self, label=label, size=(60,-1))
 123                 gsizer2.Add(b)
 124                 b.Bind(wx.EVT_BUTTON, self.OnButton)                
 125         sizer.Add(gsizer2, (6,1),(1,1), wx.EXPAND|wx.LEFT|wx.RIGHT|wx.BOTTOM, 10)
 126         self.SetSizerAndFit(sizer)
 127 
 128     #-----------------------------------------------------------------------
 129         
 130     def OnKeyPress(self, event):
 131         """
 132         ...
 133         """
 134         
 135         keycode = event.GetKeyCode()
 136         if keycode in (13, 370):
 137             self.enter()
 138         elif keycode in (43, 388):
 139             self.add()
 140         elif keycode in (45, 390):
 141             self.sub()
 142         elif keycode in (42, 387):
 143             self.mult()
 144         elif keycode in (47, 392):
 145             self.div()
 146         else:
 147             event.Skip()
 148 
 149         
 150     def OnButton(self, event):
 151         """
 152         ...
 153         """
 154         
 155         # Get title of clicked button
 156         global STACK1, STACK2, STACK3, STACK4, STATE, TEMP_NUM
 157         label = event.GetEventObject().GetLabel()
 158 
 159         if label == 'Enter':
 160             self.enter()
 161 
 162         elif label == '+':
 163             self.add()
 164 
 165         elif label == '-':
 166             self.sub()
 167 
 168         elif label == '/':
 169             self.div()
 170 
 171         elif label == '*':
 172             self.mult()
 173 
 174         elif label == 'sqrt':
 175             self.sqrt()
 176 
 177         elif label == '^':
 178             self.power()
 179 
 180         elif label == 'Swap':
 181             self.swap()
 182 
 183         elif label == 'Del':
 184             self.delete()
 185 
 186         elif label == 'C':
 187             self.display.SetValue('')
 188 
 189         else:
 190             self.display.SetValue(self.display.GetValue() + label)
 191 
 192             
 193     def enter(self):
 194         """
 195         Enter a new number to the stack
 196         """
 197         
 198         global STACK1, STACK2, STACK3, STACK4
 199         if self.display.GetValue() != "":
 200             STACK4 = STACK3
 201             STACK3 = STACK2
 202             STACK2 = STACK1
 203             STACK1 = self.frac_to_decimal()
 204             self.updateDisplay()
 205         else:
 206             STACK4 = STACK3
 207             STACK3 = STACK2
 208             STACK2 = STACK1
 209             STACK1 = 0
 210             self.updateDisplay()
 211 
 212                         
 213     def swap(self):
 214         """
 215         Swap contents of stack1 and stack2
 216         """
 217         
 218         global STACK1, STACK2
 219         STACK1, STACK2 = STACK2, STACK1
 220         self.updateDisplay()
 221 
 222 
 223     def delete(self):
 224         """
 225         Delete number from stack1 display and shift remaining results down stack
 226         """
 227         
 228         global STACK1, STACK2, STACK3, STACK4
 229         STACK1 = STACK2
 230         STACK2 = STACK3
 231         STACK3 = STACK4
 232         STACK4 = 0
 233         self.updateDisplay()
 234 
 235         
 236     def add(self):
 237         """
 238         Add stack1 and display or contents of stack
 239         """
 240         
 241         global STACK1, STACK2, STACK3, STACK4
 242         if self.display.GetValue() != "":
 243             STACK1 = STACK1 + self.frac_to_decimal()
 244             self.updateDisplay()
 245         else:
 246             STACK1 = STACK2 + STACK1
 247             STACK2 = STACK3
 248             STACK3 = STACK4
 249             STACK4 = 0
 250             self.updateDisplay()
 251 
 252                             
 253     def sub(self):
 254         """
 255         Subtract stack1 and display or contents of stack
 256         """
 257         
 258         global STACK1, STACK2, STACK3, STACK4
 259         if self.display.GetValue() != "":
 260             STACK1 = STACK1 - self.frac_to_decimal()
 261             self.updateDisplay()
 262         else:
 263             STACK1 = STACK2 - STACK1
 264             STACK2 = STACK3
 265             STACK3 = STACK4
 266             STACK4 = 0
 267             self.updateDisplay()
 268 
 269    
 270     def mult(self):
 271         """
 272         Multiply stack1 and display or contents of stack
 273         """
 274         
 275         global STACK1, STACK2, STACK3, STACK4
 276         if self.display.GetValue() != "":
 277             STACK1 = STACK1 * self.frac_to_decimal()
 278             self.updateDisplay()
 279         else:
 280             STACK1 = STACK2 * STACK1
 281             STACK2 = STACK3
 282             STACK3 = STACK4
 283             STACK4 = 0
 284             self.updateDisplay()
 285 
 286 
 287     def div(self):
 288         """
 289         Divide stack1 and display or contents of stack
 290         """
 291         
 292         global STACK1, STACK2, STACK3, STACK4
 293         if self.display.GetValue() != "":
 294             STACK1 = STACK1 / self.frac_to_decimal()
 295             self.updateDisplay()
 296         else:
 297             STACK1 = STACK2 / STACK1
 298             STACK2 = STACK3
 299             STACK3 = STACK4
 300             STACK4 = 0
 301             self.updateDisplay()
 302 
 303 
 304     def sqrt(self):
 305         """
 306         Take the square root of display or stack1
 307         """
 308         
 309         global STACK1, STACK2, STACK3, STACK4
 310         if self.display.GetValue() != "":
 311             if self.display.GetValue() >= 0:
 312                 STACK4 = STACK3
 313                 STACK3 = STACK2
 314                 STACK2 = STACK1
 315                 STACK1 = math.sqrt(self.frac_to_decimal())
 316                 self.updateDisplay()
 317             else:
 318                 dlg = wx.MessageDialog(self, "Neg numbers not valid",
 319                                        wx.OK|wx.CANCEL)
 320                 dlg.ShowModal()
 321                 dlg.Destroy()
 322         else:
 323             if STACK1 >= 0:
 324                 STACK1 = math.sqrt(STACK1)
 325                 self.updateDisplay()
 326             else:
 327                 dlg = wx.MessageDialog(self, "Neg numbers not valid",
 328                                        wx.OK|wx.CANCEL)
 329                 dlg.ShowModal()
 330                 dlg.Destroy()
 331 
 332 
 333     def power(self):
 334         """
 335         Raise to the power
 336         """
 337         
 338         global STACK1, STACK2, STACK3, STACK4
 339         if self.display.GetValue() != "":
 340             STACK1 = STACK1 ** self.frac_to_decimal()
 341             self.updateDisplay()
 342         else:
 343             STACK1 = STACK2 ** STACK1
 344             STACK2 = STACK3
 345             STACK3 = STACK4
 346             STACK4 = 0
 347             self.updateDisplay()            
 348 
 349             
 350     def updateDisplay(self):
 351         """
 352         Update display
 353         """
 354         
 355         global STACK1, STACK2, STACK3, STACK4
 356         if self.rbox.GetSelection() == 0:
 357             S4 = self.fraction_str(STACK4)
 358             S3 = self.fraction_str(STACK3)
 359             S2 = self.fraction_str(STACK2)
 360             S1 = self.fraction_str(STACK1)
 361         elif self.rbox.GetSelection() == 1:
 362             S4 = str(STACK4 * 12)
 363             S3 = str(STACK3 * 12)
 364             S2 = str(STACK2 * 12)
 365             S1 = str(STACK1 * 12)
 366         else:
 367             S4 = str(STACK4)
 368             S3 = str(STACK3)
 369             S2 = str(STACK2)
 370             S1 = str(STACK1)
 371             
 372         self.display4.SetLabel(S4)
 373         self.display3.SetLabel(S3)
 374         self.display2.SetLabel(S2)
 375         self.display1.SetLabel(S1)
 376         self.display.SetValue('')
 377         self.display.SetFocus()
 378 
 379 
 380     def frac_to_decimal(self):
 381         """
 382         Convert feet-inch input to decimal feet
 383         """
 384         
 385         s = self.display.GetValue()
 386         s.strip()
 387         if s.find("'") == -1:
 388             dec_ft = float(s)
 389         else:
 390             if s.find(',') == -1:
 391                 ft_index = s.find("'")
 392                 ft = int(s[:ft_index])
 393                 inch = int(s[(ft_index+1):])
 394                 dec_ft = ft + inch/12.0
 395             else:
 396                 ft_index = s.find("'")
 397                 in_index = s.find(' ')
 398                 fr_index = s.find(',')
 399                 ft = int(s[:ft_index])
 400                 inch = int(s[(ft_index+1):in_index])
 401                 frac = float(Fraction(s[(in_index+1):fr_index] + "/" + s[(fr_index+1):]))
 402                 dec_ft = ft + (inch + frac)/12
 403         return dec_ft
 404 
 405 
 406     def fraction_str(self, num):
 407         """
 408         Convert decimal ft to ft-in string
 409         """
 410         
 411         ft_int = int(num)
 412         inch = (num - int(num))* 12
 413         inch_int = int(inch)
 414         frac = (inch - inch_int) * 8
 415         numerator = int(frac)
 416         if numerator == 0:
 417             frac_text = ""
 418         elif inch >= (11 + (7.4999/8)):
 419             ft_int = ft_int + 1
 420             inch_int = 0
 421             frac_text = ""
 422         elif numerator == 8:
 423             inch_int = inch_int + 1
 424             frac_text = ""
 425         else:
 426             denominator = 8
 427             if (frac - numerator) < 0.5:
 428                 while numerator % 2 == 0:
 429                     numerator = numerator / 2
 430                     denominator = denominator / 2
 431             else:
 432                 numerator = numerator + 1
 433                 while numerator % 2 == 0:
 434                     numerator = numerator / 2
 435                     denominator = denominator / 2
 436             frac_text = str(numerator) + '/' + str(denominator)
 437         frac_str = str(ft_int) + "' " + str(inch_int) + " " + frac_text
 438         return frac_str
 439 
 440 
 441     def conversion(self, event):
 442         self.updateDisplay()
 443                 
 444 #---------------------------------------------------------------------------
 445         
 446 if __name__ == '__main__':
 447     calculator = wx.App(False)
 448     calc = MainFrame(None)
 449     calc.Show(True)
 450     calculator.MainLoop()


Sample five

img_sample_five.png

   1 # sample_five.py
   2 
   3 """
   4 
   5 Author : Sneekula
   6 Do some simple math operations with
   7 wx.Choice(parent,id,pos,size,choices,style)
   8 https://www.daniweb.com/programming/software-development/threads/128350/starting-wxpython-gui-code/3#post1823238
   9 
  10 
  11 """
  12 
  13 import wx
  14 from math import *
  15 
  16 #---------------------------------------------------------------------------
  17 
  18 # List of math operations Python understands
  19 # x and/or y values are pulled from the edit boxes
  20 
  21 operation_list = [
  22 'x + y',
  23 'x - y',
  24 'x * y',
  25 'x / y',
  26 'x**y',
  27 'sqrt(x)',
  28 'exp(x)', 
  29 'log(x)', 
  30 'log10(x)', 
  31 'degrees(x)',
  32 'radians(x)',
  33 'sin(x)',
  34 'cos(x)',
  35 'tan(x)',
  36 'asin(x)',
  37 'acos(x)',
  38 'atan(x)'
  39 ]
  40 
  41 # class MyFrame
  42 
  43 #---------------------------------------------------------------------------
  44 
  45 class MyFrame(wx.Frame):
  46     def __init__(self, parent, title, operation_list):
  47         wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(350, 270))
  48 
  49         self.SetIcon(wx.Icon('./icons/wxwin.ico', wx.BITMAP_TYPE_ICO))
  50 
  51         #------------
  52         
  53         self.SetBackgroundColour('green')
  54 
  55         #------------
  56         
  57         # Create choice widget for the math operations
  58         self.choice = wx.Choice(self, wx.ID_ANY, choices=operation_list)
  59         # Select item 0 (first item) in choices list to show
  60         self.choice.SetSelection(0)
  61         self.choice.SetToolTip(wx.ToolTip('Select one math operation'))
  62         # Bind the checkbox events to action
  63         self.choice.Bind(wx.EVT_CHOICE, self.onAction)
  64         
  65         edit_label1 = wx.StaticText(self, wx.ID_ANY, 'Enter x :')
  66         self.edit1 = wx.TextCtrl(self, wx.ID_ANY, value="1", size=(200, 20))
  67         
  68         edit_label2 = wx.StaticText(self, wx.ID_ANY, 'Enter y :')
  69         self.edit2 = wx.TextCtrl(self, wx.ID_ANY, value="1", size=(200, 20))
  70             
  71         edit_label3 = wx.StaticText(self, wx.ID_ANY, 'Result :')
  72         self.edit3 = wx.TextCtrl(self, wx.ID_ANY, value="", size=(200, 20))
  73         self.edit3.SetToolTip(wx.ToolTip('Double click to move data to x'))
  74         self.edit3.Bind(wx.EVT_LEFT_DCLICK, self.onDoubleClick)
  75         
  76         self.button = wx.Button(self, wx.ID_ANY, label='Calculate')
  77         # Bind mouse event to action
  78         self.button.Bind(wx.EVT_BUTTON, self.onAction)
  79 
  80         #------------
  81         
  82         # Hgap is between columns, vgap between rows
  83         sizer = wx.GridBagSizer(vgap=0, hgap=0)
  84         
  85         # Pos=(row, column)
  86         sizer.Add(edit_label1, pos=(0,0), flag=wx.ALL|wx.EXPAND, border=10)
  87         sizer.Add(self.edit1, pos=(0,1), flag=wx.ALL|wx.EXPAND, border=10)
  88         sizer.Add(edit_label2, pos=(1,0), flag=wx.ALL|wx.EXPAND, border=10)
  89         sizer.Add(self.edit2, pos=(1,1), flag=wx.ALL|wx.EXPAND, border=10)
  90         # Span=(rowspan, columnspan)
  91         sizer.Add(self.choice, pos=(2,0), span=(1, 2), flag=wx.ALL|wx.EXPAND, border=10)
  92         sizer.Add(self.button, pos=(3,0), span=(1, 2), flag=wx.ALL|wx.EXPAND, border=10)
  93         sizer.Add(edit_label3, pos=(4,0), flag=wx.ALL|wx.EXPAND, border=10)
  94         sizer.Add(self.edit3, pos=(4,1), flag=wx.ALL|wx.EXPAND, border=10)
  95 
  96         self.SetSizerAndFit(sizer)
  97 
  98     #-----------------------------------------------------------------------
  99         
 100     def onAction(self, event):
 101         """
 102         ...
 103         """
 104         
 105         op = self.choice.GetStringSelection()
 106         x = float(self.edit1.GetValue())
 107         y = float(self.edit2.GetValue())
 108         
 109         if y == 0.0 and op == 'x / y' :
 110             result = 'division by zero error'
 111         else:
 112             result = eval(op)
 113             
 114         # Print result, type(result)
 115         self.edit3.SetValue(str(result))
 116 
 117         
 118     def onDoubleClick(self, event):
 119         """
 120         If edit3 has been doubleclicked, transfer value to edit1
 121         """
 122         
 123         val = self.edit3.GetValue()
 124         self.edit1.ChangeValue(val)
 125 
 126 #---------------------------------------------------------------------------
 127 
 128 app = wx.App(0)
 129 # Create the MyFrame instance and show it
 130 MyFrame(None, 'Do math stuff', operation_list).Show()
 131 app.MainLoop()


Sample six

img_sample_six.png

   1 # sample_six.py
   2 
   3 """
   4 
   5 Create a calulator button layout with wx.GridSizer().
   6 Then add a few things to form a tiny wxPython calculator.
   7 https://stackoverflow.com/questions/16435607/range-object-does-not-support-item-assignment-trying-to-use-old-python-code
   8 
   9 """
  10 
  11 import wx
  12 
  13 # class MyFrame
  14 
  15 #---------------------------------------------------------------------------
  16 
  17 class MyFrame(wx.Frame):
  18     """
  19     Make a frame, inherits wx.Frame.
  20     """
  21     def __init__(self):
  22         # Create a frame/window, no parent
  23         wx.Frame.__init__(self, None, wx.ID_ANY, 'Tiny calculator',
  24                           pos=(300, 150), size=(300, 200))
  25 
  26         self.SetIcon(wx.Icon('./icons/wxwin.ico', wx.BITMAP_TYPE_ICO))
  27         self.SetBackgroundColour('purple')
  28 
  29         #------------
  30         
  31         # Main sizer
  32         vsizer = wx.BoxSizer(wx.VERTICAL)
  33 
  34         self.edit = wx.TextCtrl(self, -1, value="", size=(165, 20))
  35 
  36         # Follows layout of calculator keys
  37         self.btn_list = [
  38         '7', '8', '9', '/', 'c',
  39         '4', '5', '6', '*', 'bs',
  40         '1', '2', '3', '-', '**',
  41         '0', '.', '=', '+', 'neg'
  42         ]
  43 
  44         #------------
  45         
  46         # wx.GridSizer(rows, cols, vgap, hgap)
  47         gsizer = wx.GridSizer(4, 5, 2, 2)
  48 
  49         self.btn = list(range(len(self.btn_list)))
  50         for ix, b_label in enumerate(self.btn_list):
  51             # Set up a consecutive unique id for each button
  52             id = 1000 + ix
  53             self.btn[ix] = wx.Button(self, id, label=b_label, size=(20, 20))
  54             # The gridsizer fills left to right one row at a time
  55             gsizer.Add(self.btn[ix], 0, wx.ALL|wx.EXPAND, border=2)
  56             self.btn[ix].Bind(wx.EVT_BUTTON, self.btnClick)
  57 
  58         #------------
  59             
  60         # Now add the whole thing to the main sizer and set it
  61         vsizer.Add(self.edit, 0, wx.EXPAND)
  62         vsizer.Add(gsizer, 1, wx.EXPAND)
  63         self.SetSizer(vsizer)
  64 
  65     #-----------------------------------------------------------------------
  66 
  67     def btnClick(self, event):
  68         """
  69         ...
  70         """
  71         
  72         # Get the label of the button clicked
  73         label = self.btn_list[event.GetId() - 1000]
  74         e_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  75             '+', '-', '*', '/', '**', '.']
  76         
  77         if label in e_list:
  78             self.edit.SetValue(self.edit.GetValue() + label)
  79         elif label == 'neg':
  80             # Negate, note eval() takes care of double negate
  81             self.edit.SetValue('-' + self.edit.GetValue())
  82         elif label == 'c':
  83             # Cclear
  84             self.edit.SetValue('')
  85         elif label == 'bs':
  86             # Backspace
  87             self.edit.SetValue(self.edit.GetValue()[:-1])
  88         elif label == '=':
  89             str1 = self.edit.GetValue()
  90             # Prevent folks from being nasty with eval()
  91             if not str1 or str1[0] not in '0123456789-+.':
  92                 self.edit.SetValue('unrecognized operation')
  93                 return
  94             while str1[0] == '0':
  95                 # Avoid leading zero (octal) error with eval()
  96                 str1 = str1[1:]
  97             if '/' in str1 and '.' not in str1:
  98                 # Turn into floating point division
  99                 str1 = str1 + '.0'
 100             try:
 101                 self.edit.SetValue(str(eval(str1)))
 102             except ZeroDivisionError:
 103                 self.edit.SetValue('division by zero error')
 104         else:
 105             self.edit.SetValue('unrecognized operation')
 106 
 107 #---------------------------------------------------------------------------
 108             
 109 app = wx.App(0)
 110 # Create MyFrame instance and show the frame
 111 MyFrame().Show()
 112 app.MainLoop()


Sample seven

img_sample_seven.png

   1 # sample_seven.py
   2 
   3 """
   4 
   5 Author : Sneekula
   6 Use slider inputs to calculate cost of petrol in the USA and Europe.
   7 https://www.daniweb.com/programming/software-development/threads/128350/starting-wxpython-gui-code/2#post1823238
   8 
   9 """
  10 
  11 import wx
  12 
  13 # class MyFrame
  14 
  15 #---------------------------------------------------------------------------
  16 
  17 class MyFrame(wx.Frame):
  18     def __init__(self, parent, mytitle, mysize):
  19         wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
  20 
  21         self.SetIcon(wx.Icon('./icons/wxwin.ico', wx.BITMAP_TYPE_ICO))        
  22         self.SetBackgroundColour("yellow")
  23 
  24         #------------
  25         
  26         # Create input widgets
  27 
  28         self.panel = wx.Panel(self, wx.ID_ANY)
  29         self.panel.SetDoubleBuffered(True)  # No flickering
  30         
  31         # Label for slider1
  32         label_s1 = wx.StaticText(self.panel, wx.ID_ANY, "US cents per US Gallon :")
  33         
  34         # Can only use integer values!!!
  35         # Initial value = 450, min value = 300, max value = 600
  36         self.slider1 = wx.Slider(self.panel, wx.ID_ANY, 450, 300, 600, size=(320, 40),
  37             style=wx.SL_HORIZONTAL|wx.SL_LABELS)
  38         
  39         # Label for slider2
  40         label_s2 = wx.StaticText(self.panel, wx.ID_ANY, "Euro cents per Liter :")
  41         
  42         # Initial value = 150, min value = 100, max value = 200
  43         self.slider2 = wx.Slider(self.panel, wx.ID_ANY, 150, 100, 200, size=(320, 40),
  44             style=wx.SL_HORIZONTAL|wx.SL_LABELS)
  45         
  46         # Label for slider3
  47         label_s3 = wx.StaticText(self.panel, wx.ID_ANY, "US cents per Euro :")
  48         
  49         # Initial value = 160, min value = 100, max value = 200
  50         self.slider3 = wx.Slider(self.panel, wx.ID_ANY, 160, 100, 200, size=(320, 40),
  51             style=wx.SL_HORIZONTAL|wx.SL_LABELS)
  52 
  53         # Bind all mouse slider marker drags to the same action
  54         self.Bind(wx.EVT_SLIDER, self.onAction)
  55 
  56         # Create an output widget
  57         self.label = wx.StaticText(self.panel, wx.ID_ANY, "")
  58 
  59         #------------
  60         
  61         # Use a vertical boxsizer for the widget placement
  62         sizer_v = wx.BoxSizer(wx.VERTICAL)
  63         sizer_h = wx.BoxSizer(wx.HORIZONTAL)
  64         sizer_v.Add(label_s1, 0, flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=10)
  65         sizer_v.Add(self.slider1, 0, flag=wx.ALL|wx.EXPAND, border=5)
  66         sizer_v.Add(label_s2, 0, flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=10)
  67         sizer_v.Add(self.slider2, 0, flag=wx.ALL|wx.EXPAND, border=5)
  68         sizer_v.Add(label_s3, 0, flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=10)
  69         sizer_v.Add(self.slider3, 0, flag=wx.ALL|wx.EXPAND, border=5)
  70         sizer_v.Add(self.label, 0, flag=wx.ALL|wx.EXPAND, border=10)
  71         sizer_h.Add(sizer_v, 0, flag=wx.ALL|wx.EXPAND, border=15)        
  72 
  73         self.panel.SetSizer(sizer_h)
  74 
  75         # Show opening result
  76         self.onAction(None)
  77 
  78     #-----------------------------------------------------------------------
  79 
  80     def onAction(self, event):
  81         """
  82         Some action code.
  83         """
  84         
  85         s = "The result... \n\n"
  86         
  87         # Gives integer cents values, convert to $ and Euro
  88         us_price = self.slider1.GetValue()/100.0
  89         euro_price = self.slider2.GetValue()/100.0
  90         euro_cost = self.slider3.GetValue()/100.0
  91         
  92         # 1 US gal = 3.785 liters
  93         s1 = "In the USA $%.2f/gal = $%.2f/liter = %.2f Euro/liter\n" % \
  94             (us_price, us_price/3.785, us_price/(3.785*euro_cost))
  95         s2 = "In Europe  $%.2f/gal = $%.2f/liter = %.2f Euro/liter" % \
  96             (euro_price*euro_cost*3.785, euro_price*euro_cost, euro_price)
  97         
  98         self.label.SetLabel(s + s1 + s2)
  99 
 100 #---------------------------------------------------------------------------
 101         
 102 app = wx.App()
 103 # Create the MyFrame instance and then show the frame
 104 frm = MyFrame(None, 'The petrol sliders', (380, 345))
 105 frm.Show(True)
 106 app.MainLoop()


Sample eight

img_sample_eight.png

   1 # sample_eight.py
   2 
   3 """
   4 
   5 A simple mortgage calulator using wxPython.
   6 Author : Lardmeister
   7 Checked it out with the online mortgage calculator at:
   8 http://www.mortgage-calc.com/mortgage/simple.php
   9 https://www.daniweb.com/programming/software-development/threads/128350/starting-wxpython-gui-code#post626319
  10 
  11 """
  12 
  13 import wx
  14 import math
  15 
  16 # class MyFrame
  17 
  18 #---------------------------------------------------------------------------
  19 
  20 class MyFrame(wx.Frame):
  21     """
  22     Frame and widgets to handle input and output of mortgage calc.
  23     """
  24     def __init__(self, parent, id, title):
  25         wx.Frame.__init__(self, parent, id, title)
  26 
  27         self.SetIcon(wx.Icon('./icons/wxwin.ico', wx.BITMAP_TYPE_ICO))
  28 
  29         #------------
  30         
  31         # Add panel, labels, text and sizer widgets
  32         panel = wx.Panel(self, -1)
  33         panel.SetBackgroundColour('orange')
  34         
  35         label1 = wx.StaticText(panel, -1, "Enter total loan amount :")
  36         label2 = wx.StaticText(panel, -1, "Enter annual interest (%) :")
  37         label3 = wx.StaticText(panel, -1, "Enter years to pay :")
  38 
  39         label1.SetForegroundColour('white')
  40         label2.SetForegroundColour('white')
  41         label3.SetForegroundColour('white')
  42         
  43         self.loan = wx.TextCtrl(panel, -1, "100000")
  44         self.interest = wx.TextCtrl(panel, -1, "6.5")
  45         self.years = wx.TextCtrl(panel, -1, "30")
  46         
  47         self.calc_btn = wx.Button(panel, -1, ' Perform Mortgage Calculation ')
  48         self.calc_btn.SetBackgroundColour('light blue')
  49         self.calc_btn.Bind(wx.EVT_BUTTON, self.onCalc)
  50         
  51         info = "Modify the above data to your needs !"
  52         self.result = wx.TextCtrl(panel, -1, info, size=(290, 100),
  53                                   style=wx.TE_MULTILINE)
  54 
  55         #------------
  56         
  57         # Use gridbagsizer for layout of widgets
  58         sizer = wx.GridBagSizer(vgap=5, hgap=10)
  59         sizer.Add(label1, pos=(0, 0))
  60         sizer.Add(self.loan, pos=(0, 1))  # row 0, column 1
  61         sizer.Add(label2, pos=(1, 0))
  62         sizer.Add(self.interest, pos=(1, 1))
  63         sizer.Add(label3, pos=(2, 0))
  64         sizer.Add(self.years, pos=(2, 1))
  65         sizer.Add(self.calc_btn, pos=(3, 0), span=(1, 2))
  66         # Span=(1, 2) --> allow to span over 2 columns 
  67         sizer.Add(self.result, pos=(4, 0), span=(1, 2))
  68         
  69         # Use boxsizer to add border around sizer
  70         border = wx.BoxSizer()
  71         border.Add(sizer, 0, wx.ALL, 20)
  72         panel.SetSizerAndFit(border)
  73         
  74         self.Fit()
  75 
  76     #-----------------------------------------------------------------------
  77         
  78     def onCalc(self, event):
  79         """
  80         Do the mortgage calcuations.
  81         """
  82         
  83         # Get the values from the input widgets
  84         principal = float(self.loan.GetValue())
  85         interest = float(self.interest.GetValue())
  86         years = float(self.years.GetValue())
  87         
  88         # Calculate        
  89         interestRate = interest/(100 * 12)
  90         paymentNum = years * 12
  91         paymentVal = principal * \
  92                      (interestRate/(1-math.pow((1+interestRate), (-paymentNum))))
  93 
  94         # Show the result
  95         resultStr1 = "Your monthly payment will be $%.2f for\n" % paymentVal
  96         resultStr2 = "a %.1f year $%.2f loan at %.2f%s interest" % \
  97                      (years, principal, interest, '%') 
  98         self.result.SetValue(resultStr1 + resultStr2) 
  99         
 100 #---------------------------------------------------------------------------
 101         
 102 app = wx.App()
 103 frame = MyFrame(None, -1, "Mortgage calculator")
 104 frame.Show()
 105 app.MainLoop()


Sample nine

img_sample_nine.png

   1 # sample_nine.py
   2 
   3 """
   4 
   5 Experiments with wxPython's wx.Notebook() widget.
   6 Author : Vegaseat
   7 Converting distance, area and volume units
   8 Tested with Python25 and wxPython28 - 11aug2008
   9 Tested with Python3.x and wxPython4.x
  10 
  11 """
  12 
  13 import wx
  14 
  15 # class MyNotebook
  16 # class MyPage
  17 
  18 #---------------------------------------------------------------------------
  19         
  20 # These are the conversion dictionaries ...
  21 # (note that units won't appear in that order)
  22 distD ={}
  23 
  24 # All scale factors are relative to the first unit below
  25 distD['meter'] = 1.0
  26 distD['micron'] = 1000000.0
  27 distD['millimeter'] = 1000.0
  28 distD['centimeter'] = 100.0
  29 distD['kilometer'] = 0.001
  30 distD['inch'] = 100.0/2.54
  31 distD['foot'] = 100.0/30.48
  32 distD['yard'] = 100.0/91.44
  33 distD['mile'] = 0.001/1.609344
  34 distD['rod'] = 1.0/5.029
  35 
  36 
  37 areaD = {}
  38 
  39 # All scale factors are relative to the first unit below
  40 areaD['sq meter'] = 1.0
  41 areaD['sq millimeter'] = 1000000.0
  42 areaD['sq centimeter'] = 10000.0
  43 areaD['sq kilometer']  = 0.000001
  44 areaD['hectare'] = 0.0001
  45 areaD['sq inch'] = 1550.003
  46 areaD['sq foot'] = 10.76391
  47 areaD['sq yard'] = 1.19599
  48 areaD['acre'] = 0.0002471054
  49 areaD['sq mile'] = 0.0000003861022
  50 
  51 
  52 volD = {}
  53 
  54 # All scale factors are relative to the first unit below
  55 volD['cubic meter'] = 1.0
  56 volD['microliter'] = 1000000000.0
  57 volD['milliliter'] = 1000000.0
  58 volD['liter'] = 1000.0
  59 volD['pint(US)'] = 2113.376
  60 volD['quart(US)'] = 1056.688
  61 volD['gallon(US)'] = 264.172
  62 volD['cubic inch'] = 61023.74
  63 volD['cubic foot'] = 35.31467
  64 volD['cubic yard'] = 1.307951
  65 
  66 #---------------------------------------------------------------------------
  67 
  68 class MyNotebook(wx.Frame):
  69     def __init__(self, parent, title, distD, areaD, volD):
  70         wx.Frame.__init__(self, parent, wx.ID_ANY, title,
  71                           size=(490, 400))
  72 
  73         self.SetIcon(wx.Icon('./icons/wxwin.ico', wx.BITMAP_TYPE_ICO))
  74 
  75         #------------
  76         
  77         # style=wx.NB_TOP is default
  78         # Could use style=wx.NB_BOTTOM
  79         nb = wx.Notebook(self, wx.ID_ANY)
  80         
  81         # MyPage(parent, conversion dictionary, preselected choice)
  82         self.page1 = MyPage(nb, distD, 3)
  83         self.page2 = MyPage(nb, areaD, 2)
  84         self.page3 = MyPage(nb, volD, 0)
  85         nb.AddPage(self.page1, "Distance Conversion")
  86         nb.AddPage(self.page2, "Area Conversion")
  87         nb.AddPage(self.page3, "Volume Conversion")
  88         
  89         # Start with page1 active
  90         self.page1.SetFocus()
  91 
  92 #---------------------------------------------------------------------------
  93         
  94 class MyPage(wx.Panel):
  95     """
  96     each panel instance creates the notbook page content
  97     from the given conversion dictionary convD
  98     """
  99     def __init__(self, parent, convD, preselect):
 100         wx.Panel.__init__(self, parent, wx.ID_ANY)
 101         
 102         oatmeal3 = '#FCFFE1'
 103         self.SetBackgroundColour(oatmeal3)
 104 
 105         self.convD = convD
 106         # print("convD :", self.convD)
 107 
 108         #------------
 109         
 110         # Create list of possible units
 111         items = convD.keys()
 112         self.options = (list(items))
 113         
 114         self.radiobox1 = wx.RadioBox(self, wx.ID_ANY,
 115                                      "Select a unit to convert from",
 116                                      choices=self.options, style=wx.VERTICAL)
 117         # Set radio button 1 as selected (first button is 0)
 118         self.radiobox1.SetSelection(preselect)
 119         # Bind mouse click to an action
 120         self.radiobox1.Bind(wx.EVT_RADIOBOX, self.onAction)
 121 
 122         self.radiobox2 = wx.RadioBox(self, wx.ID_ANY,
 123                                      "Select a unit to convert to  ",
 124                                      choices=self.options, style=wx.VERTICAL)
 125         # Set radio button 1 as selected (first button is 0)
 126         self.radiobox2.SetSelection(preselect)
 127         # Bind mouse click to an action
 128         self.radiobox2.Bind(wx.EVT_RADIOBOX, self.onAction)
 129 
 130         # Additional widgets
 131         self.label1 = wx.StaticText(self, wx.ID_ANY, "" )
 132         self.label2 = wx.StaticText(self, wx.ID_ANY, "" )
 133 
 134         self.edit1 = wx.TextCtrl(self, wx.ID_ANY, value="1.0",
 135                                  size=(150, 20), style=wx.TE_PROCESS_ENTER)
 136         # Respond to enter key when focus is on edit1
 137         self.edit1.Bind(wx.EVT_TEXT_ENTER, self.onAction)
 138 
 139         self.edit2 = wx.TextCtrl(self, wx.ID_ANY, value="",
 140             size=(150, 20), style=wx.TE_PROCESS_ENTER)
 141 
 142         self.button = wx.Button(self, wx.ID_ANY, label='Convert')
 143         self.button.Bind(wx.EVT_BUTTON, self.onAction)
 144 
 145         #------------
 146         
 147         # Use box sizers to layout the widgets
 148         # Nest the 3 vertical sizers in the horizontal sizer later
 149         sizer_v1 = wx.BoxSizer(wx.VERTICAL)
 150         sizer_v2 = wx.BoxSizer(wx.VERTICAL)
 151         sizer_v3 = wx.BoxSizer(wx.VERTICAL)
 152         sizer_h = wx.BoxSizer(wx.HORIZONTAL)
 153         # Add the widgets to the corresponding vertical sizer
 154         sizer_v1.Add(self.radiobox1, 0, flag=wx.ALL, border=10)
 155         sizer_v1.Add(self.label1, 0, wx.LEFT|wx.RIGHT|wx.TOP, 10)
 156         sizer_v1.Add(self.edit1, 0, wx.LEFT|wx.RIGHT, 10)
 157         # Add a spacer to position the button lower ...
 158         sizer_v2.Add((0, 225), 0, wx.ALL, 10)
 159         sizer_v2.Add(self.button, 0, wx.ALL, 10)
 160         sizer_v3.Add(self.radiobox2, 0, wx.ALL, 10)
 161         sizer_v3.Add(self.label2, 0, wx.LEFT|wx.RIGHT|wx.TOP, 10)
 162         sizer_v3.Add(self.edit2, 0, wx.LEFT|wx.RIGHT, 10)
 163         # Put the 3 vertical sizers into the horizontal sizer
 164         sizer_h.Add(sizer_v1, 0)
 165         sizer_h.Add(sizer_v2, 0)
 166         sizer_h.Add(sizer_v3, 0)
 167         
 168         # It's the horizontal sizer you have to set
 169         self.SetSizer(sizer_h)
 170 
 171         #------------
 172         
 173         # Show present selection
 174         self.onAction(None)
 175 
 176     #-----------------------------------------------------------------------
 177 
 178     def onAction(self, event):
 179         """
 180         Show the selected choice.
 181         """
 182         
 183         index1 = self.radiobox1.GetSelection()
 184         unit1 = self.options[index1]
 185         # print(unit1)  # test
 186         
 187         s = "Enter a value (%s):" % unit1
 188         self.label1.SetLabel(s)
 189         
 190         # Dito for radio box #2
 191         index2 = self.radiobox2.GetSelection()
 192         unit2 = self.options[index2]
 193         
 194         # print(unit2)  # test
 195         s = "Result (%s):" % unit2
 196         self.label2.SetLabel(s)
 197 
 198         value = float(self.edit1.GetValue())
 199         factor1 = self.convD[unit1]
 200         factor2 = self.convD[unit2]
 201         result = factor2 * value/factor1
 202         self.edit2.ChangeValue(str(result))
 203 
 204 #---------------------------------------------------------------------------
 205 
 206 app = wx.App(True)
 207 frm = MyNotebook(None, "Converting distance, area and volume units",
 208                  distD, areaD, volD)
 209 frm.SetDoubleBuffered(True)
 210 frm.Show(True)
 211 app.MainLoop()


Sample ten

img_sample_ten.png

   1 # sample_ten.py
   2 
   3 """
   4 
   5 A few experiments with wxPython's
   6 Test wx.Slider (move the slider to calculate F and C values)
   7 wx.Slider(parent, id, value, minValue, maxValue, pos, size, style)
   8 style -->
   9 wx.SL_VERTICAL  displays the slider vertically
  10 wx.SL_HORIZONTAL  displays the slider horizontally
  11 wx.SL_AUTOTICKS  displays tick marks
  12 wx.SL_LABELS  displays minimum, maximum and value labels
  13 Author : Dietrich - 17NOV2008
  14 https://www.daniweb.com/programming/software-development/threads/128350/starting-wxpython-gui-code/
  15 
  16 """
  17 
  18 import wx
  19 
  20 # class MyFrame
  21 
  22 #---------------------------------------------------------------------------
  23 
  24 class MyFrame(wx.Frame):
  25     def __init__(self, parent, mytitle, mysize):
  26         wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
  27         
  28         self.SetIcon(wx.Icon('./icons/wxwin.ico', wx.BITMAP_TYPE_ICO))
  29         self.SetBackgroundColour('white')
  30 
  31         #------------
  32 
  33         self.panel = wx.Panel(self, wx.ID_ANY)
  34         self.panel.SetDoubleBuffered(True)  # No flickering
  35         
  36         # All values are integer values only
  37         self.slider = wx.Slider(self.panel, wx.ID_ANY,
  38                                 value=-40,  # The initial value of slider position
  39                                 minValue=-100,
  40                                 maxValue=400,
  41                                 pos=(10, 10),
  42                                 size=(620, 40),
  43                                 style=wx.SL_HORIZONTAL|wx.SL_LABELS)
  44         # Respond to changes in slider position
  45         self.Bind(wx.EVT_SLIDER, self.sliderUpdate)
  46        
  47         self.label = wx.StaticText(self.panel, wx.ID_ANY, label="", pos=(70, 60))
  48         self.label.SetForegroundColour("blue")
  49         # self.label.SetBackgroundColour("yellow")
  50 
  51         #------------
  52         
  53         # Use initial setting
  54         self.sliderUpdate()
  55 
  56     #-----------------------------------------------------------------------
  57         
  58     def sliderUpdate(self, event=None):
  59         """
  60         Slider position is an integer, as the slider is moved
  61         Fahrenheit and Celcius are calculated in real time
  62         """
  63         
  64         pos = self.slider.GetValue()
  65         
  66         f = str(round(pos * 9.0/5 + 32, 2))
  67         c = str(round((pos - 32)*5/9.0, 2))
  68         v = str(pos)
  69         
  70         s1 = v + " degree Fahrenheit is " + c + " degree Celcius \n"
  71         s2 = v + " degree Celcius is " + f + " degree Fahrenheit"
  72         
  73         self.label.SetLabel(s1 + s2)
  74 
  75 #---------------------------------------------------------------------------
  76         
  77 app = wx.App(0)
  78 # Create a MyFrame instance and show the frame
  79 mytitle = 'Calculate Fahrenheit and Celcius'
  80 width = 660
  81 height = 150
  82 MyFrame(None, mytitle, (width, height)).Show()
  83 app.MainLoop()


Sample eleven

img_sample_eleven.png

   1 # sample_eleven.py
   2 
   3 """
   4 Author : Vegaseat
   5 Use wxPython's wx.ComboBox() to select different units of measurement
   6 Then convert the area associated with the selections
   7 Tested with Python24 and wxPython26 - 21oct2005
   8 Tested with Python3.x and wxPython4.x
   9 http://www.daniweb.com/software-development/python/code/216651/wxpython-combobox-demo
  10 
  11 """
  12 
  13 import wx
  14 
  15 # class MyPanel
  16 
  17 #---------------------------------------------------------------------------
  18 
  19 # Create an empty dictionary
  20 areaD = {}
  21 
  22 # Populate dictionary with units and conversion factors relative to sqmeter = 1.0
  23 # This minimizes the total number of conversion factors
  24 areaD['sqmeter'] = 1.0
  25 areaD['sqmillimeter'] = 1000000.0
  26 areaD['sqcentimeter'] = 10000.0
  27 areaD['sqkilometer'] = 0.000001
  28 areaD['hectare'] = 0.0001
  29 areaD['sqinch'] = 1550.003
  30 areaD['sqfoot'] = 10.76391
  31 areaD['sqyard'] = 1.19599
  32 areaD['acre'] = 0.0002471054
  33 areaD['sqmile'] = 0.0000003861022
  34 
  35 #---------------------------------------------------------------------------
  36 
  37 class MyPanel(wx.Panel):
  38     """
  39     Class MyPanel creates a panel with 2 comboboxes and more, inherits wx.Panel
  40     (putting your components/widgets on a panel gives additional versatility)
  41     """
  42     def __init__(self, parent, id):
  43         # No pos and size given, so panel defaults to fill the parent frame
  44         wx.Panel.__init__(self, parent, id)
  45         
  46         self.SetBackgroundColour((255,228,196)) # bisque
  47 
  48         #------------
  49         
  50         # Create a sorted list for the combo boxes
  51         items = areaD.keys()
  52         areaList = (sorted(items))
  53 
  54         #------------
  55         
  56         # No size given, so the text determines the needed label size
  57         st1 = wx.StaticText(self, -1, "Convert from:", (10, 10))
  58 
  59         # Create a combo box to select units of measurement to convert from
  60         self.combo1 = wx.ComboBox(self, -1,
  61                                   value=areaList[0],
  62                                   pos=wx.Point(10, 30),
  63                                   size=wx.Size(120,30),
  64                                   choices=areaList)
  65 
  66         # Optional tooltip
  67         self.combo1.SetToolTip(wx.ToolTip("Select unit from dropdown-list"))
  68 
  69         st2 = wx.StaticText(self, -1, "Convert to:", pos=wx.Point(150, 10))
  70 
  71        # Create a combo box to select units of measurement to convert to
  72         self.combo2 = wx.ComboBox(self, -1,
  73                                   value=areaList[0],
  74                                   pos=wx.Point(150, 30),
  75                                   size=wx.Size(120, 30),
  76                                   choices=areaList)
  77 
  78         st3 = wx.StaticText(self, -1, "Value to convert:", pos=wx.Point(10, 70))
  79 
  80         self.edit1 = wx.TextCtrl(self, -1, value="1",
  81                                  pos=wx.Point(10, 90),
  82                                  size=wx.Size(175, 25))
  83         self.edit1.SetBackgroundColour((255,255,197)) # suds yellow
  84 
  85         self.button1 = wx.Button(self, -1, label="Do the Conversion ...",
  86                                  pos=wx.Point(10, 130), size=wx.Size(175, 28))
  87         # Respond to button click event
  88         self.button1.Bind(wx.EVT_BUTTON, self.button1Click, self.button1)
  89 
  90         st4 = wx.StaticText(self, -1, "Result:", (10, 170))
  91 
  92         self.edit2 = wx.TextCtrl(self, -1, value="",
  93                                  pos=wx.Point(10, 190),
  94                                  size=wx.Size(350, 25))
  95         self.edit2.SetBackgroundColour((217,255,219)) # vegaseat green
  96 
  97     #-----------------------------------------------------------------------
  98         
  99     def button1Click(self,event):
 100         """
 101         Conversion button has been clicked.
 102         """
 103         
 104         unit1 = self.combo1.GetValue()
 105         unit2 = self.combo2.GetValue()
 106         x = float(self.edit1.GetValue())
 107         y = self.convertArea(x, unit1, unit2)
 108         
 109         if y < 0.001:
 110                 str1 = "%f %s = %0.12f %s" % (x, unit1, y, unit2) # Very small y
 111         elif y > 1000:
 112             str1 = "%f %s = %0.3f %s" % (x, unit1, y, unit2) # Very large y
 113         else:
 114             str1 = "%f %s = %f %s" % (x, unit1, y, unit2) # 6 decimals is default
 115             
 116         self.edit2.SetValue(str1)
 117         
 118 
 119     def convertArea(self, x, unit1, unit2):
 120         """
 121         Convert area x of unit1 to area of unit2 and return area, on error return False.
 122         """
 123         
 124         if (unit1 in areaD) and (unit2 in areaD):
 125             factor1 = areaD[unit1]
 126             factor2 = areaD[unit2]
 127             return factor2*x/factor1
 128         else:
 129             return False
 130 
 131 #---------------------------------------------------------------------------
 132 
 133 app = wx.App()
 134 # Create a window/frame, no parent, -1 is default ID, title, size
 135 frame = wx.Frame(None, -1, "Convert area", size = (400, 300))
 136 frame.SetIcon(wx.Icon('./icons/wxwin.ico', wx.BITMAP_TYPE_ICO))
 137 # Call the derived class, -1 is default ID, can also use wx.ID_ANY
 138 MyPanel(frame,-1)
 139 # Show the frame
 140 frame.Show(True)
 141 # Start the event loop
 142 app.MainLoop()


Download source

source.zip


Additional Information

Link :

- - - - -

https://wiki.wxpython.org/TitleIndex

https://docs.wxpython.org/


Thanks to

Jan Bodnar (sample_one / two.py coding), Daniel Ramos (sample_two.py coding), DaniWeb.com, BridgeGuy, Sneekula, Lardmeister, Vegaseat, Dietrich, the wxPython community...


About this page

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

01/05/21 - Ecco (Created page for wxPython Phoenix). 14/01/23 - Ecco (Updated page and "source.zip" for Python 3.10.5).


Comments

- blah, blah, blah....

How to create a calculator - Part 1 (Phoenix) (last edited 2023-01-14 15:24:57 by Ecco)

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