Python wxpython 写一个计算器
时间: 2023-05-12 19:03:46 浏览: 121
Python使用wxPython实现计算器
好的,我可以为您提供一个 Python wxpython 写的计算器的代码示例:
```
import wx
class Calculator(wx.Frame):
def __init__(self, parent, title):
super(Calculator, self).__init__(parent, title=title, size=(300, 250))
self.InitUI()
self.Centre()
self.Show()
def InitUI(self):
vbox = wx.BoxSizer(wx.VERTICAL)
self.display = wx.TextCtrl(self, style=wx.TE_RIGHT)
vbox.Add(self.display, flag=wx.EXPAND | wx.TOP | wx.BOTTOM, border=4)
grid = wx.GridSizer(5, 4, 5, 5)
grid.AddMany([(wx.Button(self, label='7'), 0, wx.EXPAND),
(wx.Button(self, label='8'), 0, wx.EXPAND),
(wx.Button(self, label='9'), 0, wx.EXPAND),
(wx.Button(self, label='/'), 0, wx.EXPAND),
(wx.Button(self, label='4'), 0, wx.EXPAND),
(wx.Button(self, label='5'), 0, wx.EXPAND),
(wx.Button(self, label='6'), 0, wx.EXPAND),
(wx.Button(self, label='*'), 0, wx.EXPAND),
(wx.Button(self, label='1'), 0, wx.EXPAND),
(wx.Button(self, label='2'), 0, wx.EXPAND),
(wx.Button(self, label='3'), 0, wx.EXPAND),
(wx.Button(self, label='-'), 0, wx.EXPAND),
(wx.Button(self, label='0'), 0, wx.EXPAND),
(wx.Button(self, label='.'), 0, wx.EXPAND),
(wx.Button(self, label='C'), 0, wx.EXPAND),
(wx.Button(self, label='+'), 0, wx.EXPAND),
(wx.Button(self, label='='), 0, wx.EXPAND)])
vbox.Add(grid, proportion=1, flag=wx.EXPAND)
self.SetSizer(vbox)
for i in range(0, 16):
self.Bind(wx.EVT_BUTTON, self.OnButtonClick, id=i)
def OnButtonClick(self, event):
button = event.GetEventObject()
label = button.GetLabel()
prev = self.display.GetValue()
if label == '=':
try:
result = str(eval(prev))
except:
result = 'Error'
self.display.SetValue(result)
elif label == 'C':
self.display.SetValue('')
else:
self.display.SetValue(prev + label)
if __name__ == '__main__':
app = wx.App()
Calculator(None, title='Calculator')
app.MainLoop()
```
希望这个代码能够帮到您!
阅读全文