利用Python制作一个简易的计算器并在HTML页面显示出来
时间: 2024-10-15 20:12:26 浏览: 31
使用Python制作一个简易的计算器并将其嵌入到HTML页面,通常涉及前后端分离的概念。首先,你需要创建一个简单的Python脚本作为后端处理计算逻辑,然后通过HTML和JavaScript在前端构建用户界面。以下是基本步骤:
**Python部分 (backend) - calculator.py**
```python
# calculator.py
def calculate(num1, operator, num2):
if operator == '+':
return num1 + num2
elif operator == '-':
return num1 - num2
elif operator == '*':
return num1 * num2
elif operator == '/':
return num1 / num2
else:
return "Invalid operator"
# 接收前端请求并返回结果
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/calculate', methods=['POST'])
def get_result():
data = request.get_json()
result = calculate(data['num1'], data['operator'], data['num2'])
return jsonify({'result': str(result)})
if __name__ == '__main__':
app.run(debug=True)
```
**HTML部分 (frontend) - index.html**
```html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Simple Calculator</title>
</head>
<body>
<form id="calculator-form" action="/calculate" method="post">
<input type="number" name="num1" placeholder="Number 1">
<select name="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="number" name="num2" placeholder="Number 2">
<button type="submit">Calculate</button>
</form>
<div id="result"></div>
<script>
document.getElementById('calculator-form').addEventListener('submit', function(e) {
e.preventDefault();
var formData = new FormData(this);
fetch('/calculate', {method: 'POST', body: formData})
.then(response => response.json())
.then(data => {
document.getElementById('result').innerText = data.result;
});
});
</script>
</body>
</html>
```
**相关问题--:**
1. 这种做法如何实现前后端数据交互?
2. Python的Flask库在该示例中起到了什么作用?
3. 如何部署这个Python应用以便外部访问?
阅读全文