用python实现一个电子算盘
时间: 2023-12-27 17:04:59 浏览: 235
可以使用Python中的tkinter库构建电子算盘界面,并结合Python的数学运算功能实现计算功能。以下是一个简单的示例代码:
```
import tkinter as tk
class Calculator:
def __init__(self, master):
self.master = master
master.title("电子算盘")
# 创建显示屏
self.display = tk.Entry(master, width=30, justify="right")
self.display.grid(row=0, column=0, columnspan=4)
# 创建数字按钮
for i in range(10):
btn = tk.Button(master, text=str(i), command=lambda x=i: self.add_digit(x))
btn.grid(row=(9-i)//3+1, column=(i-1)%3)
# 创建操作符按钮
plus = tk.Button(master, text="+", command=lambda: self.add_operator("+"))
plus.grid(row=4, column=3)
minus = tk.Button(master, text="-", command=lambda: self.add_operator("-"))
minus.grid(row=3, column=3)
times = tk.Button(master, text="*", command=lambda: self.add_operator("*"))
times.grid(row=2, column=3)
divide = tk.Button(master, text="/", command=lambda: self.add_operator("/"))
divide.grid(row=1, column=3)
equal = tk.Button(master, text="=", command=lambda: self.calculate())
equal.grid(row=5, column=3)
clear = tk.Button(master, text="清空", command=lambda: self.clear())
clear.grid(row=1, column=2)
# 初始化数据
self.current_num = 0
self.current_op = "+"
self.last_num = 0
self.last_op = "="
self.reset_flag = True
def add_digit(self, digit):
if self.reset_flag:
self.display.delete(0, tk.END)
self.reset_flag = False
current_text = self.display.get()
if current_text == "0":
current_text = str(digit)
else:
current_text += str(digit)
self.display.delete(0, tk.END)
self.display.insert(0, current_text)
def add_operator(self, operator):
self.current_num = int(self.display.get())
self.calculate()
self.current_op = operator
self.reset_flag = True
def calculate(self):
self.last_num = eval(str(self.last_num) + self.last_op + str(self.current_num))
self.last_op = self.current_op
self.current_num = 0
self.reset_flag = True
if self.last_op == "=":
self.display.delete(0, tk.END)
self.display.insert(0, str(self.last_num))
else:
self.display.delete(0, tk.END)
self.display.insert(0, "0")
def clear(self):
self.last_num = 0
self.last_op = "="
self.current_num = 0
self.current_op = "+"
self.display.delete(0, tk.END)
self.display.insert(0, "0")
self.reset_flag = True
root = tk.Tk()
app = Calculator(root)
root.mainloop()
```
阅读全文