Python:用wxpython写的计算器

source: http://blog.sina.com.cn/s/blog_a3f0d68201016uhz.html


前阵子稍微学了下wxpython,写了个简易的计算器作为练习,详细代码如下:

#coding=utf8
import wx
import math

class MainFrame(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, 'Calculator', size=(343,470),
                          style=wx.DEFAULT_FRAME_STYLE ^ (wx.RESIZE_BORDER | wx.MINIMIZE_BOX | wx.MAXIMIZE_BOX))
        panel = wx.Panel(self)
        gridSizer = wx.GridSizer(rows=5, cols=5, hgap=5, vgap=5)
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        self.resultStr = ''

        #-----StatusBar--------------------------------
        self.statusBar = wx.StatusBar(self, -1)
        self.statusBar.SetStatusText('Copyright @ fudaoji')

        #----Static-----------------------------------
        self.staticText = wx.StaticText(panel, -1, '')
        #----TextCtrl----------------------------
        self.textCtrl = wx.TextCtrl(panel, -1, '',style=wx.TE_MULTILINE|wx.TE_RICH2)
        font = wx.Font(18, wx.ROMAN, wx.NORMAL, wx.BOLD, underline=False)
        self.textCtrl.SetFont(font)
        #-------Buttons-------------------------------------------------
        self.buttonLabels = "7 8 9 DEL AC 4 5 6 * / 1 2 3 + - 0 % PI \
                            e sqrt ^ sin cos tan log ln ( ) . =".split()
        self.buttons = []
        self.flag = [] #index of button
        btnLength = len(self.buttonLabels)
        for i in range(btnLength):
            self.buttons.append(wx.Button(panel, i, size=(63,52),
                                          label=("%s" % self.buttonLabels[i])))
            gridSizer.Add(self.buttons[i], 0, 0)
        mainSizer.Add(self.textCtrl, 1, wx.EXPAND)
        mainSizer.Add(self.staticText, 0.7, wx.EXPAND)
        mainSizer.Add(gridSizer, 5, wx.EXPAND)
        panel.SetSizerAndFit(mainSizer)

        self.Bind(wx.EVT_BUTTON, self.OnResult, self.buttons[-1])

        #a list of handlers
        self.funcList = [self.OnClick]*(btnLength-1)
        self.funcList[3] = self.OnPop
        self.funcList[4] = self.OnClear
        self.funcList[17] = self.chgPi
        self.funcList[18] = self.chgE
        for i in range(btnLength-1):
            self.buttonBind(i)

    def setText(self, value):
        '''set the value of TextCtrl'''
        self.textCtrl.SetValue(value)
        
    def chgE(self, event):
        '''e=math.e'''
        self.resultStr += str(math.e)
        self.setText(self.resultStr)
        event.Skip()
        
    def chgPi(self, event):
        '''pi=3.1416'''
        self.resultStr += str(math.pi)
        self.setText(self.resultStr)
        event.Skip()
        
    def buttonBind(self, index):
        self.buttons[index].Bind(wx.EVT_LEFT_DOWN, self.funcList[index])
                
    def OnPop(self, event):
        '''click button "DEL" to Undo'''
        self.resultStr = self.resultStr[:-1]
        self.setText(self.resultStr)
        event.Skip()
        
    def OnClear(self, event):
        '''click button "AC" to clear screen'''
        self.textCtrl.SetValue('')
        self.resultStr = ''
        event.Skip()
        
    def OnResult(self, event):
        mathFunc = ['sqrt', 'sin', 'cos', 'tan']
        result = 'Error'
        for func in mathFunc:
            if func in self.resultStr:
                try:
                    result = str(eval('math.'+self.resultStr))
                    break
                except: pass
        if '^' in self.resultStr:
            try:
                temp = self.resultStr.split('^')
                result = str(eval('pow('+temp[0]+','+temp[1]+')'))
            except: pass
        elif 'ln' in self.resultStr:
            try:
                result = str(eval('math.log'+self.resultStr[2:]))
            except: pass
        elif 'log' in self.resultStr:
            try:
                result = str(eval('math.log'+self.resultStr[3:]+'/math.log(10)'))
            except: pass
        else:    
            try:
                result = str(eval(self.resultStr))
            except: pass
        self.resultStr = result
        self.setText(result)
        event.Skip()
        
    def OnClick(self, event):
        self.resultStr += self.buttonLabels[event.GetId()]
        self.setText(self.resultStr)
        event.Skip()
            


if __name__ == "__main__":
    app = wx.PySimpleApp()
    frame = MainFrame(None, -1)
    frame.Show()
    app.MainLoop()



用wxpython写的计算器

用wxpython写的计算器

posted @ 2022-04-29 22:37  WORDLESS  阅读(109)  评论(0编辑  收藏  举报