基于Python的多功能计算器设计与实现
项目概述
本项目旨在开发一个功能完整的命令行与图形化双模式计算器,涵盖基本四则运算、取模、幂运算及三角函数计算。通过模块化函数设计与tkinter界面集成,实现用户友好的交互体验。
核心功能实现
1. 命令行计算器逻辑
print("多功能科学计算器已启动")
running = True
while running:
operation = input("选择操作 (+, -, *, /, %, **, sin, cos, tan): ").strip()
if operation == '0':
break
try:
num1 = float(input("输入第一个数值: "))
if operation in ['+', '-', '*', '/', '%']:
num2 = float(input("输入第二个数值: "))
result = eval(f"{num1} {operation} {num2}")
print(f"结果: {result}")
elif operation == '**':
power = int(input("输入指数: "))
print(f"结果: {num1 ** power}")
elif operation in ['sin', 'cos', 'tan']:
import math
angle_deg = num1
angle_rad = math.radians(angle_deg)
func_map = {'sin': math.sin, 'cos': math.cos, 'tan': math.tan}
print(f"{operation.upper()}({angle_deg}°) = {func_map[operation](angle_rad)}")
else:
print("不支持的操作符")
except Exception as e:
print(f"计算错误: {e}")
2. 图形化界面(tkinter)
import tkinter as tk
from tkinter import messagebox
class ScientificCalculator:
def __init__(self):
self.window = tk.Tk()
self.window.title("科学计算器 - 20211414")
self.window.geometry("400x500")
self.window.resizable(False, False)
# 输入显示区域
self.display = tk.Text(self.window, height=2, width=20, font=("Arial", 16), wrap="none")
self.display.pack(pady=10)
# 结果显示区域
self.result_display = tk.Text(self.window, height=1, width=20, font=("Arial", 14), bg="lightgray")
self.result_display.pack(pady=5)
# 按钮布局
buttons = [
('C', 0, 0), ('/', 0, 1), ('*', 0, 2), ('-', 0, 3),
('7', 1, 0), ('8', 1, 1), ('9', 1, 2), ('+', 1, 3),
('4', 2, 0), ('5', 2, 1), ('6', 2, 2), ('=', 2, 3),
('1', 3, 0), ('2', 3, 1), ('3', 3, 2), ('%', 3, 3),
('0', 4, 0), ('.', 4, 1), ('sin', 4, 2), ('cos', 4, 3),
('tan', 5, 0), ('**', 5, 1), ('(', 5, 2), (')', 5, 3)
]
for text, row, col in buttons:
btn = tk.Button(self.window, text=text, width=8, height=2,
command=lambda t=text: self.button_click(t))
btn.grid(row=row+1, column=col, padx=2, pady=2)
self.window.protocol("WM_DELETE_WINDOW", self.on_closing)
def button_click(self, value):
current = self.display.get("1.0", "end-1c")
if value == '=':
try:
expression = current.replace('×', '*').replace('%', '/100')
result = eval(expression)
self.result_display.delete("1.0", "end")
self.result_display.insert("end", f"{result}")
except:
self.result_display.delete("1.0", "end")
self.result_display.insert("end", "错误")
elif value == 'C':
self.display.delete("1.0", "end")
self.result_display.delete("1.0", "end")
elif value in ['sin', 'cos', 'tan']:
try:
angle = float(current)
import math
rad = math.radians(angle)
func_map = {'sin': math.sin, 'cos': math.cos, 'tan': math.tan}
result = func_map[value](rad)
self.result_display.delete("1.0", "end")
self.result_display.insert("end", f"{result:.6f}")
except:
self.result_display.delete("1.0", "end")
self.result_display.insert("end", "无效角度")
else:
self.display.insert("end", value)
def on_closing(self):
if messagebox.askokcancel("退出确认", "确定要关闭计算器吗?"):
self.window.destroy()
if __name__ == "__main__":
app = ScientificCalculator()
app.window.mainloop()
关键技术点
- 使用
eval()实现表达式求值,需对特殊符号进行预处理 - 通过
math.radians()实现角度到弧度转换 - 采用面向对象封装提高代码可维护性
- 异常处理保障程序稳定性
- 事件驱动机制实现按钮响应
运行效果
程序提供清晰的界面布局,支持连续计算、表达式编辑和错误提示。所有数学函数均调用标准库函数确保精度。