本文目录导读:

我来帮你写一个简易计算器,这里提供几个不同版本的实现:
纯Python命令行版本(最简单)
def simple_calculator():
"""命令行简易计算器"""
print("简易计算器")
print("支持操作: +, -, *, /")
while True:
try:
# 获取用户输入
num1 = float(input("请输入第一个数字: "))
operator = input("请输入运算符 (+,-,*,/,q退出): ")
if operator == 'q':
print("再见!")
break
num2 = float(input("请输入第二个数字: "))
# 执行计算
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
if num2 == 0:
print("错误:不能除以0!")
continue
result = num1 / num2
else:
print("无效运算符!")
continue
print(f"结果: {result}")
print("-" * 30)
except ValueError:
print("错误:请输入有效数字!")
except Exception as e:
print(f"发生错误: {e}")
if __name__ == "__main__":
simple_calculator()
图形界面版本(Tkinter)
import tkinter as tk
class Calculator:
def __init__(self, root):
self.root = root
self.root.title("简易计算器")
self.root.geometry("300x400")
# 显示结果
self.result_var = tk.StringVar()
self.result_var.set("0")
# 创建显示框
self.display = tk.Entry(
root,
textvariable=self.result_var,
font=("Arial", 20),
justify="right",
state="readonly"
)
self.display.pack(fill="x", padx=10, pady=10, ipady=10)
# 创建按钮
self.create_buttons()
def create_buttons(self):
# 按钮布局
buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '=', '+'
]
# 创建按钮框架
button_frame = tk.Frame(self.root)
button_frame.pack(fill="both", expand=True, padx=10, pady=10)
# 创建按钮
row = 0
col = 0
for button_text in buttons:
cmd = lambda x=button_text: self.click(x)
btn = tk.Button(
button_frame,
text=button_text,
font=("Arial", 16),
command=cmd,
relief="groove",
bd=2
)
btn.grid(row=row, column=col, sticky="nsew", padx=2, pady=2)
col += 1
if col > 3:
col = 0
row += 1
# 清除按钮(单独放置)
clear_btn = tk.Button(
button_frame,
text="C",
font=("Arial", 16),
command=self.clear,
relief="groove",
bd=2,
bg="#ff9999"
)
clear_btn.grid(row=row, column=0, sticky="nsew", padx=2, pady=2)
# 删除按钮
delete_btn = tk.Button(
button_frame,
text="⌫",
font=("Arial", 16),
command=self.delete,
relief="groove",
bd=2,
bg="#99ff99"
)
delete_btn.grid(row=row, column=1, columnspan=3, sticky="nsew", padx=2, pady=2)
# 配置网格权重
for i in range(4):
button_frame.grid_columnconfigure(i, weight=1)
for i in range(5):
button_frame.grid_rowconfigure(i, weight=1)
def click(self, value):
current = self.result_var.get()
if value == '=':
try:
# 安全执行计算
result = eval(current)
self.result_var.set(str(result))
except:
self.result_var.set("错误")
elif value in ['+', '-', '*', '/']:
# 运算符处理
if current and current[-1] not in '+-*/':
self.result_var.set(current + value)
elif current[-1:] in '+-*/':
# 替换运算符
self.result_var.set(current[:-1] + value)
elif value == '.':
# 小数点处理
if current.count('.') == 0 or current[-1] in '+-*/':
self.result_var.set(current + value)
else:
# 数字处理
if current == "0":
self.result_var.set(value)
else:
self.result_var.set(current + value)
def clear(self):
self.result_var.set("0")
def delete(self):
current = self.result_var.get()
if len(current) > 1:
self.result_var.set(current[:-1])
else:
self.result_var.set("0")
if __name__ == "__main__":
root = tk.Tk()
calculator = Calculator(root)
root.mainloop()
Web版本(Flask + HTML)
# 需安装: pip install flask
from flask import Flask, request, render_template_string
app = Flask(__name__)
HTML_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>简易计算器</title>
<style>
body { font-family: Arial; display: flex; justify-content: center; padding: 50px; }
.calculator { background: #f4f4f4; padding: 20px; border-radius: 10px; box-shadow: 0 2px 5px rgba(0,0,0,0.2); }
input[type="text"] { width: 200px; padding: 10px; font-size: 20px; margin-bottom: 10px; }
table { margin: 0 auto; }
button { width: 50px; height: 50px; font-size: 18px; margin: 2px; cursor: pointer; border: none; background: white; border-radius: 5px; }
button:hover { background: #ddd; }
</style>
</head>
<body>
<div class="calculator">
<h2>简易计算器</h2>
<form method="POST">
<input type="text" name="expression" value="{{ expression }}" readonly>
<table>
{% for row in buttons %}
<tr>
{% for btn in row %}
<td><button type="submit" name="expression" value="{{ expression }}{{ btn }}">{{ btn }}</button></td>
{% endfor %}
</tr>
{% endfor %}
<tr>
<td colspan="2"><button type="submit" name="expression" value="">C</button></td>
<td colspan="2"><button type="submit" name="expression" value="=" style="background: #4CAF50; color: white;">=</button></td>
</tr>
</table>
</form>
{% if result %}
<p>结果: {{ result }}</p>
{% endif %}
</div>
</body>
</html>
"""
@app.route('/', methods=['GET', 'POST'])
def calculator():
expression = ""
result = None
if request.method == 'POST':
expression = request.form.get('expression', '')
if expression.endswith('='):
expression = expression[:-1]
try:
result = eval(expression)
expression = str(result)
except:
result = "错误"
# 按钮布局
buttons = [
['7', '8', '9', '/'],
['4', '5', '6', '*'],
['1', '2', '3', '-'],
['0', '.', '/', '+']
]
return render_template_string(
HTML_TEMPLATE,
buttons=buttons,
expression=expression,
result=result
)
if __name__ == '__main__':
app.run(debug=True)
使用说明
- 命令行版本:直接运行即可,体验最简单
- Tkinter版本:需要安装tkinter(通常Python自带)
- Web版本:需要先安装Flask,然后运行,浏览器访问
http://127.0.0.1:5000
关键知识点
- 输入处理:使用 try/except 处理异常
- 字符串操作:处理运算符和数字
- 界面设计:布局和交互逻辑
- 安全考虑:使用eval()时需谨慎
选择适合你需求的版本,有任何具体问题可以问我!