**
效果展示
**
**
代码介绍
**
导入库:
导入 tkinter 和 messagebox,用于创建图形用户界面和弹出对话框。
主类 BMIApp:
定义了BMI计算器的所有组件和功能。
构造函数 init:
初始化界面元素,如标签、输入框和按钮,并设置它们在网格中的位置。
身高和体重的增加功能:
increase_height 和 increase_weight 方法实现了每次点击按钮时身高或体重增加1的功能,并更新对应的计数器。
计算BMI的功能:
calculate_bmi 方法计算并显示用户的BMI值,检查输入的有效性。
布局配置:
通过 grid 方法设置界面元素的位置,并通过 grid_columnconfigure 和 grid_rowconfigure 使内容居中。
弹出对话框:
使用 messagebox.showinfo 和 messagebox.showerror 显示结果和错误信息。
主循环:
在 if name == “main” 中启动应用。
**
部分源码
**
##完整源码gongzhonghao:PandaYY回复1015
import tkinter as tk
from tkinter import messagebox
class BMIApp:
def __init__(self, root):
self.root = root
self.root.title("BMI计算器")
# 设置列和行的权重,使内容居中
root.grid_columnconfigure(0, weight=1)
root.grid_columnconfigure(1, weight=1)
root.grid_columnconfigure(2, weight=1)
root.grid_rowconfigure(3, weight=1)
self.name_label = tk.Label(root, text="姓名:")
self.name_label.grid(row=0, column=0, padx=10, pady=10, sticky="w")
self.name_entry = tk.Entry(root)
self.name_entry.grid(row=0, column=1, padx=10, pady=10)
self.height_label = tk.Label(root, text="身高(cm):")
self.height_label.grid(row=1, column=0, padx=10, pady=10, sticky="w")
self.height_entry = tk.Entry(root)
self.height_entry.grid(row=1, column=1, padx=10, pady=10)
self.weight_label = tk.Label(root, text="体重(kg):")
self.weight_label.grid(row=2, column=0, padx=10, pady=10, sticky="w")
self.weight_entry = tk.Entry(root)
self.weight_entry.grid(row=2, column=1, padx=10, pady=10)
self.height_output_label = tk.Label(root, text="身高增加次数:")
self.height_output_label.grid(row=3, column=0, padx=10, pady=10, sticky="w")
self.height_output_var = tk.IntVar()
self.height_output_var.set(0)
self.height_output = tk.Label(root, textvariable=self.height_output_var)
self.height_output.grid(row=3, column=1, padx=10, pady=10)
self.weight_output_label = tk.Label(root, text="体重增加次数:")
self.weight_output_label.grid(row=4, column=0, padx=10, pady=10, sticky="w")
self.weight_output_var = tk.IntVar()
self.weight_output_var.set(0)
self.weight_output = tk.Label(root, textvariable=self.weight_output_var)
self.weight_output.grid(row=4, column=1, padx=10, pady=10)
self.calc_bmi_button = tk.Button(root, text="计算BMI", command=self.calculate_bmi)
self.calc_bmi_button.grid(row=5, column=0, columnspan=2, padx=10, pady=10)
self.height_increase_button = tk.Button(root, text="身高增加1cm", command=self.increase_height)
self.height_increase_button.grid(row=6, column=0, padx=10, pady=10)
self.weight_increase_button = tk.Button(root, text="体重增加1kg", command=self.increase_weight)
self.weight_increase_button.grid(row=6, column=1, padx=10, pady=10)
self.height_count = 0
self.weight_count = 0
footer_label = tk.Label(root, text="by ---- Panda", bg='#f0f0f0', fg='black')
footer_label.grid(row=7, column=0, columnspan=3, pady=10, sticky="s")