1、给定角色定位
2、提出要求
import tkinter as tk
class Calculator:
def __init__(self):
self.root = tk.Tk()
self.root.title("计算器")
# 用一个字符串变量存储输入和输出结果
self.var = tk.StringVar()
self.var.set("")
self.entry = tk.Entry(self.root, textvariable=self.var, font=("微软雅黑", 20), bd=5, justify='right')
self.entry.grid(row=0, column=0, columnspan=4, sticky='we')
# 创建各个按钮
self.create_button("C", self.clear, row=1, column=0)
self.create_button("←", self.backspace, row=1, column=1)
self.create_button("/", lambda:self.button_click("/"), row=1, column=2)
self.create_button("*", lambda:self.button_click("*"), row=1, column=3)
self.create_button("7", lambda:self.button_click("7"), row=2, column=0)
self.create_button("8", lambda:self.button_click("8"), row=2, column=1)
self.create_button("9", lambda:self.button_click("9"), row=2, column=2)
self.create_button("-", lambda:self.button_click("-"), row=2, column=3)
self.create_button("4", lambda:self.button_click("4"), row=3, column=0)
self.create_button("5", lambda:self.button_click("5"), row=3, column=1)
self.create_button("6", lambda:self.button_click("6"), row=3, column=2)
self.create_button("+", lambda:self.button_click("+"), row=3, column=3)
self.create_button("1", lambda:self.button_click("1"), row=4, column=0)
self.create_button("2", lambda:self.button_click("2"), row=4, column=1)
self.create_button("3", lambda:self.button_click("3"), row=4, column=2)
self.create_button("=", self.calculate, row=4, column=3, rowspan=2)
self.create_button("0", lambda:self.button_click("0"), row=5, column=0, columnspan=2)
self.create_button(".", lambda:self.button_click("."), row=5, column=2)
def start(self):
self.root.mainloop()
def create_button(self, text, command, row, column, rowspan=1, columnspan=1):
button = tk.Button(self.root, text=text, width=5, height=2, font=("微软雅黑", 16), command=command)
button.grid(row=row, column=column, rowspan=rowspan, columnspan=columnspan, padx=2, pady=2)
def button_click(self, text):
# 在字符串变量末尾添加新的数字或符号
self.var.set(self.var.get() + text)
def clear(self):
# 清空字符串变量的值
self.var.set("")
def backspace(self):
# 删除字符串变量末尾的一个字符
self.var.set(self.var.get()[:-1])
def calculate(self):
try:
# 利用eval函数计算表达式的值
result = eval(self.var.get())
# 显示计算结果
self.var.set(str(result))
except ZeroDivisionError:
self.var.set("除数不能为0")
except:
self.var.set("计算错误")
if __name__ == "__main__":
calculator = Calculator()
calculator.start()
效果还是不错的,界面也还可以,简单的加减乘除运算都没有问题
1.现在加入就送内含5-18美元的 ChatGPT 开发者账号
2.外面卖888元的ChatGPT系列课程星球内免费看
3.不用魔法,直接使用 ChatGPT
4.大量 ChatGPT 相关帖子学习
5.可以晒自己的学习成果,和大家一起分享