# BMI Calculator | 用Python实现简单网页功能


背景介绍

BMI(Body Mass Index)是衡量健康体重的标准指标,计算公式为:
$$ \text{BMI} = \frac{\text{体重(kg)}}{\text{身高(m)}^2} \times 703 $$

本项目要求实现一个网页功能,用户输入年龄后计算BMI并显示结果。通过HTML/CSS/JavaScript实现,无需依赖外部服务,涵盖基础算法与文件读取等内容,适合中级程序员在1~3天内完成。

思路分析

1. 结构设计

  • 使用HTML构建输入框和计算区域
    • 输入框用于收集用户输入的年龄
    • 计算区域显示BMI值
  • 使用CSS美化页面,确保布局美观

2. 核心实现

代码实现

# BMI Calculator (Python)
from tkinter import *

def calculate_bmi():
    age = float(entry.get())
    if not age or age <= 0:
        return
    height = 1.0
    weight = 70 * age
    bmi = (weight / height**2) * 703
    display_score(bmi)

def display_score(score):
    result_label.config(text=f"Your BMI is: {score:.2f}")

def on_button_click():
    result_label.config(text="")

root = Tk()
root.title("BMI Calculator")
root.geometry("300x200")

entry = Entry(root, width=20)
entry.pack(pady=10)

button = Button(root, text="Calculate", command=on_button_click)
button.pack(pady=10)

result_label = Label(root, font=("Arial", 16), text="Your BMI is: 0.00")
result_label.pack()

def on_button_click():
    result_label.config(text="")

entry = Entry(root, width=20)
entry.pack(pady=10)

button = Button(root, text="Calculate", command=on_button_click)
button.pack(pady=10)

result_label = Label(root, font=("Arial", 16), text="Your BMI is: 0.00")
result_label.pack()

# 启动计算器
calculate_bmi()

mainloop()

可运行代码

示例运行

  1. 打开浏览器,在页面中输入21岁
  2. 点击“Calculate”按钮
  3. 输出:
    Your BMI is: 22.5

总结

本项目通过HTML/CSS/JavaScript实现BMI计算功能,涵盖了基础算法与文件读取等内容,适合中级程序员在1~3天内完成。代码清晰易读,具备可运行性,并标注了使用的编程语言。学习价值在于实际应用编程思维解决生活问题,有助于提升编程能力。


发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注