赞
踩
BMI是身体质量指数(Body Mass Index)的缩写,是一种衡量人体肥胖程度的指标。它是根据人的身高和体重计算得出的,公式为:
BMI = 体重(kg)/ 身高^2(m)
其中,体重以千克为单位,身高以米为单位。根据计算结果,可以将人的体型分为偏瘦、正常、超重和肥胖四个等级。
BMI指数的范围和对应的等级如下:
完整源码如下:
- import tkinter as tk
- from tkinter import messagebox
-
- def calculate_bmi():
- try:
- height = float(height_entry.get()) / 100 # 转换为米
- weight = float(weight_entry.get())
- bmi = weight / (height * height)
- bmi = round(bmi, 1) # 保留一位小数
-
- if bmi < 18.5:
- category = "偏瘦"
- range_info = "偏瘦范围: < 18.5"
- elif bmi < 24.9:
- category = "正常"
- range_info = "正常范围: 18.5 - 24.9"
- elif bmi < 29.9:
- category = "超重"
- range_info = "超重范围: 25 - 29.9"
- else:
- category = "肥胖"
- range_info = "肥胖范围: >= 30"
-
- result_label.config(text=f"BMI指数: {bmi}")
- category_label.config(text=f"等级: {category}")
- range_label.config(text=range_info)
- except ValueError:
- messagebox.showerror("错误", "请输入有效的身高和体重!")
-
- # 创建窗口
- window = tk.Tk()
- window.title("BMI指数计算")
- window.geometry("600x400")
-
- # 创建标签和输入框
- height_label = tk.Label(window, text="身高(cm):", font=("Arial", 14))
- height_label.pack()
- height_entry = tk.Entry(window, font=("Arial", 14))
- height_entry.pack()
-
- weight_label = tk.Label(window, text="体重(kg):", font=("Arial", 14))
- weight_label.pack()
- weight_entry = tk.Entry(window, font=("Arial", 14))
- weight_entry.pack()
-
- # 创建计算按钮
- calculate_button = tk.Button(window, text="计算", command=calculate_bmi, font=("Arial", 14))
- calculate_button.pack()
-
- # 创建结果标签
- result_label = tk.Label(window, text="BMI指数: ", font=("Arial", 16, "bold"))
- result_label.pack()
-
- category_label = tk.Label(window, text="等级: ", font=("Arial", 16, "bold"))
- category_label.pack()
-
- range_label = tk.Label(window, text="", font=("Arial", 14))
- range_label.pack()
-
- # 运行窗口
- window.mainloop()
运行结果如下,身高已在计算过程中转换为米,此处是为了更方便地输入:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。