嗨害大家好鸭!我是小熊猫~
好像好久都没给大家更新啦!
这次来给大家做一个我弟刚刚做完的期末考试大作业
做一个简易计算器
要求:
- 1.要有加减乘除四个方法的编写
- 2.提交的代码悟编译错误
- 3.代码需要有基础的健壮性判断
源码、资料电子书点击这里获取
效果展示
导入模块
import tkinter as tk
实例化一个窗体对象
root = tk.Tk()
设置窗口的大小长宽为300x300出现的位置距离窗口左上角+150+150
root.geometry("295x280+150+150")
###python学习交流:660193417
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()