Python完成期末大作业:简易计算器【案例分享】

嗨害大家好鸭!我是小熊猫~

好像好久都没给大家更新啦!

这次来给大家做一个我弟刚刚做完的期末考试大作业

做一个简易计算器

要求:

  • 1.要有加减乘除四个方法的编写

  • 2.提交的代码悟编译错误

  • 3.代码需要有基础的健壮性判断

在这里插入图片描述

效果展示

请添加图片描述

在这里插入图片描述

源码、资料电子书点击这里获取

导入模块

import tkinter as tk

实例化一个窗体对象

root = tk.Tk()

设置窗口的大小长宽为300x300出现的位置距离窗口左上角+150+150

root.geometry("295x280+150+150")
root.title('计算器')
root.attributes("-alpha", 0.9)
root["background"] = "#ffffff"

先定义一个列表收集输入的内容

lists = []
result_num = tk.StringVar()
result_num.set(0)

显示数字

def append_num(i):
    lists.append(i)
    result_num.set(''.join(lists))

加减乘除

def operator(i):
    if len(lists) > 0:
        if lists[-1] in ['+', '-', '*', '/']:
            lists[-1] = i
        else:
            lists.append(i)
        result_num.set(''.join(lists))

等于

def equal():
    a = ''.join(lists)
    end_num = eval(a)
    result_num.set(end_num)
    lists.clear()
    lists.append(str(end_num))

清空

def clear():
    lists.clear()
    result_num.set(0)

按钮界面设置一下~

lable1 = tk.Label(root, textvariable=result_num, width=20, height=2, font=('宋体', 20), justify='left', background='#ffffff', anchor='se')
lable1.grid(padx=4, pady=4, row=0, column=0, columnspan=4)

button_clear = tk.Button(root, text='C', width=5, font=('宋体', 16), relief='flat', background='#C0C0C0', command=lambda: clear())
button_back = tk.Button(root, text='←', width=5, font=('宋体', 16), relief='flat', background='#C0C0C0', command=lambda: back())
button_division = tk.Button(root, text='/', width=5, font=('宋体', 16), relief='flat', background='#C0C0C0', command=lambda: operator('/'))
button_multiplication = tk.Button(root, text='x', width=5, font=('宋体', 16), relief='flat', background='#C0C0C0', command=lambda: operator('*'))
###python学习交流:660193417
button_clear            .grid(padx=4, row=1, column=0)
button_back             .grid(padx=4, row=1, column=1)
button_division         .grid(padx=4, row=1, column=2)
button_multiplication   .grid(padx=4, row=1, column=3)

button_seven = tk.Button(root, text='7', width=5, font=('宋体', 16), relief='flat', background='#FFDEAD', command=lambda: append_num('7'))
button_eight = tk.Button(root, text='8', width=5, font=('宋体', 16), relief='flat', background='#FFDEAD', command=lambda: append_num('8'))
button_nine = tk.Button(root, text='9', width=5, font=('宋体', 16), relief='flat', background='#FFDEAD', command=lambda: append_num('9'))
button_subtraction = tk.Button(root, text='—', width=5, font=('宋体', 16), relief='flat', background='#C0C0C0', command=lambda: operator('-'))

别忘记进入消息循环,显示窗口

root.mainloop()

今天的文章就是这样啦!
希望我的文章可以帮到你~

我是小熊猫,咱下篇文章再见啦(✿◡‿◡)

在这里插入图片描述

  • 15
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值