Python实验 —— 简易计算器制作

Python实验 —— 简易计算器制作

实验说明

Python 作为一门功能强大且易学的编程语言,为我们提供了丰富的工具和库,使得创造有趣的应用成为一种愉快的体验。在这个 Python 实验中,我们将一起探索并构建一个简易计算器应用程序。

计算器是计算机科学中的经典问题之一,它可以帮助我们进行基本的数学运算,同时展示了图形用户界面(GUI)设计的基础。我们将使用 Python 的 tkinter 库来创建 GUI,并结合数学库以实现计算功能。

在这个实验中,你将了解到如何使用 Python 的类、函数和图形用户界面设计,逐步搭建一个具有基本计算功能的简易计算器。这不仅是一个有趣的项目,也是提升你 Python 编程技能的绝佳机会。

实验过程

import tkinter
import math
import tkinter.messagebox

class calculator:
    #界面布局方法
    def __init__(self):
        #创建主界面,并且保存到成员属性中
        self.root = tkinter.Tk()
        self.root.minsize(280, 450)
        self.root.maxsize(280, 470)
        self.root.title('计算器')
        # 设置显式面板的变量
        self.result = tkinter.StringVar()
        self.result.set(0)
        # 设置一个全局变量  运算数字和f符号的列表
        self.lists = []
        # 添加一个用于判断是否按下运算符号的标志
        self.ispresssign = False
        # 界面布局
        self.menus()
        self.layout()
        self.root.mainloop()


    #计算器菜单界面摆放
    def menus(self):
        # 添加菜单
        # 创建总菜单
        allmenu = tkinter.Menu(self.root)
        # 添加子菜单
        filemenu = tkinter.Menu(allmenu, tearoff=0)
        # 添加选项卡
        filemenu.add_command(label='标准型(T)            Alt+1', command=self.myfunc)
        filemenu.add_command(label='科学型(S)            Alt+2', command=self.myfunc)
        filemenu.add_command(label='程序员(P)            Alt+3', command=self.myfunc)
        filemenu.add_command(label='统计信息(A)        Alt+4', command=self.myfunc)
        # 添加分割线
        filemenu.add_separator()
        # 添加选项卡
        filemenu.add_command(label='历史记录(Y)      Ctrl+H', command=self.myfunc)
        filemenu.add_command(label='数字分组(I)', command=self.myfunc)
        # 添加分割线
        filemenu.add_separator()
        # 添加选项卡
        filemenu.add_command(label='基本(B)             Ctrl+F4', command=self.myfunc)
        filemenu.add_command(label='单位转换(U)      Ctrl+U', command=self.myfunc)
        filemenu.add_command(label='日期计算(D)      Ctrl+E', command=self.myfunc)
        menu1 = tkinter.Menu(filemenu, tearoff=0)
        menu1.add_command(label='抵押(M)', command=self.myfunc)
        menu1.add_command(label='汽车租赁(V)', command=self.myfunc)
        menu1.add_command(label='油耗(mpg)(F)', command=self.myfunc)
        menu1.add_command(label='油耗(l/100km)(U)', command=self.myfunc)
        filemenu.add_cascade(label='工作表(W)', menu=menu1)
        allmenu.add_cascade(label='查看(V)', menu=filemenu)
        self.root.config(menu=allmenu)


    #计算器主界面摆放
    def layout(self):
        # 显示屏
        result = tkinter.StringVar()
        result.set(0)
        show_label = tkinter.Label(self.root, bd=3, bg='white', font=('宋体', 30), anchor='e', textvariable=self.result)
        show_label.place(x=5, y=20, width=270, height=70)
        # 功能按钮MC
        button_mc = tkinter.Button(self.root, text='MC', command=self.wait)
        button_mc.place(x=5, y=95, width=50, height=50)
        # 功能按钮MR
        button_mr = tkinter.Button(self.root, text='MR', command=self.wait)
        button_mr.place(x=60, y=95, width=50, height=50)
        # 功能按钮MS
        button_ms = tkinter.Button(self.root, text='MS', command=self.wait)
        button_ms.place(x=115, y=95, width=50, height=50)
        # 功能按钮M+
        button_mjia = tkinter.Button(self.root, text='M+', command=self.wait)
        button_mjia.place(x=170, y=95, width=50, height=50)
        # 功能按钮M-
        button_mjian = tkinter.Button(self.root, text='M-', command=self.wait)
        button_mjian.place(x=225, y=95, width=50, height=50)
        # 功能按钮←
        button_zuo = tkinter.Button(self.root, text='←', command=self.dele_one)
        button_zuo.place(x=5, y=150, width=50, height=50)
        # 功能按钮CE
        button_ce = tkinter.Button(self.root, text='CE', command=lambda: self.result.set(0))
        button_ce.place(x=60, y=150, width=50, height=50)
        # 功能按钮C
        button_c = tkinter.Button(self.root, text='C', command=self.sweeppress)
        button_c.place(x=115, y=150, width=50, height=50)
        # 功能按钮±
        button_zf = tkinter.Button(self.root, text='±', command=self.zf)
        button_zf.place(x=170, y=150, width=50, height=50)
        # 功能按钮√
        button_kpf = tkinter.Button(self.root, text='√', command=self.kpf)
        button_kpf.place(x=225, y=150, width=50, height=50)
        # 数字按钮7
        button_7 = tkinter.Button(self.root, text='7', command=lambda: self.pressnum('7'))
        button_7.place(x=5, y=205, width=50, height=50)
        # 数字按钮8
        button_8 = tkinter.Button(self.root, text='8', command=lambda: self.pressnum('8'))
        button_8.place(x=60, y=205, width=50, height=50)
        # 数字按钮9
        button_9 = tkinter.Button(self.root, text='9', command=lambda: self.pressnum('9'))
        button_9.place(x=115, y=205, width=50, height=50)
        # 功能按钮/
        button_division = tkinter.Button(self.root, text='/', command=lambda: self.presscalculate('/'))
        button_division.place(x=170, y=205, width=50, height=50)
        # 功能按钮%
        button_remainder = tkinter.Button(self.root, text='//', command=lambda:self.presscalculate('//'))
        button_remainder.place(x=225, y=205, width=50, height=50)
        # 数字按钮4
        button_4 = tkinter.Button(self.root, text='4', command=lambda: self.pressnum('4'))
        button_4.place(x=5, y=260, width=50, height=50)
        # 数字按钮5
        button_5 = tkinter.Button(self.root, text='5', command=lambda: self.pressnum('5'))
        button_5.place(x=60, y=260, width=50, height=50)
        # 数字按钮6
        button_6 = tkinter.Button(self.root, text='6', command=lambda: self.pressnum('6'))
        button_6.place(x=115, y=260, width=50, height=50)
        # 功能按钮*
        button_multiplication = tkinter.Button(self.root, text='*', command=lambda: self.presscalculate('*'))
        button_multiplication.place(x=170, y=260, width=50, height=50)
        # 功能按钮1/x
        button_reciprocal = tkinter.Button(self.root, text='1/x', command=self.ds)
        button_reciprocal.place(x=225, y=260, width=50, height=50)
        # 数字按钮1
        button_1 = tkinter.Button(self.root, text='1', command=lambda: self.pressnum('1'))
        button_1.place(x=5, y=315, width=50, height=50)
        # 数字按钮2
        button_2 = tkinter.Button(self.root, text='2', command=lambda: self.pressnum('2'))
        button_2.place(x=60, y=315, width=50, height=50)
        # 数字按钮3
        button_3 = tkinter.Button(self.root, text='3', command=lambda: self.pressnum('3'))
        button_3.place(x=115, y=315, width=50, height=50)
        # 功能按钮-
        button_subtraction = tkinter.Button(self.root, text='-', command=lambda: self.presscalculate('-'))
        button_subtraction.place(x=170, y=315, width=50, height=50)
        # 功能按钮=
        button_equal = tkinter.Button(self.root, text='=', command=lambda: self.pressequal())
        button_equal.place(x=225, y=315, width=50, height=105)
        # 数字按钮0
        button_0 = tkinter.Button(self.root, text='0', command=lambda: self.pressnum('0'))
        button_0.place(x=5, y=370, width=105, height=50)
        # 功能按钮.
        button_point = tkinter.Button(self.root, text='.', command=lambda: self.pressnum('.'))
        button_point.place(x=115, y=370, width=50, height=50)
        # 功能按钮+
        button_plus = tkinter.Button(self.root, text='+', command=lambda: self.presscalculate('+'))
        button_plus.place(x=170, y=370, width=50, height=50)


    #计算器菜单功能
    def myfunc(self):
        tkinter.messagebox.showinfo('','只是装饰而已~')


    #数字方法
    def pressnum(self,num):
        # 全局化变量
        # 判断是否按下了运算符号
        if self.ispresssign == False:
            pass
        else:
            self.result.set(0)
            # 重置运算符号的状态
            self.ispresssign = False
        if num == '.':
            num = '0.'
        # 获取面板中的原有数字
        oldnum = self.result.get()
        # 判断界面数字是否为0
        if oldnum == '0':
            self.result.set(num)
        else:
            # 连接上新按下的数字
            newnum = oldnum + num

            # 将按下的数字写到面板中
            self.result.set(newnum)


    #运算函数
    def presscalculate(self,sign):
        # 保存已经按下的数字和运算符号
        # 获取界面数字
        num = self.result.get()
        self.lists.append(num)
        # 保存按下的操作符号
        self.lists.append(sign)
        # 设置运算符号为按下状态
        self.ispresssign = True


    #获取运算结果
    def pressequal(self):
        # 获取所有的列表中的内容(之前的数字和操作)
        # 获取当前界面上的数字
        curnum = self.result.get()
        # 将当前界面的数字存入列表
        self.lists.append(curnum)
        # 将列表转化为字符串
        calculatestr = ''.join(self.lists)
        # 使用eval执行字符串中的运算即可
        endnum = eval(calculatestr)
        # 将运算结果显示在界面中
        self.result.set(str(endnum)[:10])
        if self.lists != 0:
            self.ispresssign = True
        # 清空运算列表
        self.lists.clear()


    #暂未开发说明
    def wait(self):
        tkinter.messagebox.showinfo('','功能在努力的实现...')


    #←按键功能
    def dele_one(self):
        if self.result.get() == '' or self.result.get() == '0':
            self.result.set('0')
            return
        else:
            num = len(self.result.get())
            if num > 1:
                strnum = self.result.get()
                strnum = strnum[0:num - 1]
                self.result.set(strnum)
            else:
                self.result.set('0')


    #±按键功能
    def zf(self):
        strnum = self.result.get()
        if strnum[0] == '-':
            self.result.set(strnum[1:])
        elif strnum[0] != '-' and strnum != '0':
            self.result.set('-' + strnum)


    #1/x按键功能
    def ds(self):
        dsnum = 1 / int(self.result.get())
        self.result.set(str(dsnum)[:10])
        if self.lists != 0:
            self.ispresssign = True
        # 清空运算列表
        self.lists.clear()


    #C按键功能
    def sweeppress(self):
        self.lists.clear()
        self.result.set(0)


    #√按键功能
    def kpf(self):
        strnum = float(self.result.get())
        endnum = math.sqrt(strnum)
        if str(endnum)[-1] == '0':
            self.result.set(str(endnum)[:-2])
        else:
            self.result.set(str(endnum)[:10])
        if self.lists != 0:
            self.ispresssign = True
        # 清空运算列表
        self.lists.clear()

实验分析

这是一个简易计算器的Python代码,使用了Tkinter库来创建GUI。这个计算器支持基本的加减乘除等运算,以及一些额外的功能按钮,如开方、倒数、清空等。

以下是一些函数的简要说明:

  • pressnum: 处理数字按钮的点击事件,将按下的数字追加到显示屏上。
  • presscalculate: 处理运算符号按钮的点击事件,将当前显示屏上的数字和运算符号添加到列表中,并将运算符号状态设为按下。
  • pressequal: 处理等号按钮的点击事件,将列表中的数字和运算符号组成一个表达式,使用eval计算结果,并在显示屏上显示。
  • wait: 一个未开发功能的提示框。
  • dele_one: 处理删除按钮的点击事件,删除显示屏上最后一个数字。
  • zf: 处理正负号切换按钮的点击事件,将当前显示屏上的数字变为其相反数。
  • ds: 处理倒数按钮的点击事件,将当前显示屏上的数字取倒数。
  • sweeppress: 处理清空按钮的点击事件,清空列表和显示屏。
  • kpf: 处理开平方按钮的点击事件,将当前显示屏上的数字取平方根。
    这个代码使用了Tkinter的一些基本组件,包括LabelButton等,通过回调函数处理按钮的点击事件。整体结构比较清晰,主要逻辑集中在pressnumpresscalculatepressequal等函数中。

如在此实验中遇到任何问题,均可在评论区向博主进行提问!

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Augenstern K

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值