You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python GUI BMI计算器属性错误与类型错误排查求助

Tkinter BMI计算器错误修复

我正在学习Python GUI开发,编写一款BMI计算器,希望根据用户输入返回不同提示信息,但修改代码时接连出现不同错误。

原代码

from tkinter import *
from tkinter.messagebox import *

def get_BMI():
        global heightEntry
        global weightEntry
        global nameEntry
        global BMI
        nameEntry = nameEntry.get()
        heightEntry = int(heightEntry.get())
        weightEntry = int(weightEntry.get())
        BMI = ((weightEntry * 703) // (heightEntry ** 2))

        if heightEntry <= 0 or weightEntry <= 0:
           showinfo(message='Error: height and weight must be positive values')

        elif heightEntry.isdigit() == False or weightEntry.isdigit() == False:
            showinfo(message= 'height and weight must be numbers')

        else:
            showinfo(message=f' {nameEntry} your BMI is {BMI}.')
        nameEntry.delete(0, 'end')
        weightEntry.delete(0, 'end')
        heightEntry.delete(0, 'end')

root = Tk()

root.title('BMI Calculator')

name = Label(root, text='Enter your name')
name.grid(row=1, column=0)
nameEntry = Entry(root)
nameEntry.grid(row=1, column=1)

height = Label(root, text='Enter your height (in)')
height.grid(row=2, column=0)
heightEntry = Entry(root)
heightEntry.grid(row=2, column=1
             )
weight = Label(root, text='Enter your weight(lb)')
weight.grid(row=3, column=0)
weightEntry = Entry(root)
weightEntry.grid(row=3, column=1)

calculateBMI = Button(root, text='Calculate BMI', command=get_BMI)
calculateBMI.grid(row=4, column=1)
root.mainloop()

第一次报错

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\16787\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "C:\Users\16787\AppData\Roaming\JetBrains\PyCharmCE2023.1\scratches\maincode.py", line 17, in get_BMI
    elif heightEntry.isdigit() == False or weightEntry.isdigit() == False:
AttributeError: 'int' object has no attribute 'isdigit'

报错原因

代码先把heightEntry和weightEntry的输入转成了整数,之后再调用isdigit()方法,但整数对象没有这个方法。而且验证顺序错误,应该先检查输入是否为数字,再转换为整数。

修改尝试(移除int转换)

heightEntry = heightEntry.get() #<<<<<< took off the int function
weightEntry = weightEntry.get() #<<<<<< took off the int function

第二次报错

C:\Users\16787\PycharmProjects\pythonProject\venv\Scripts\python.exe C:\Users\16787\AppData\Roaming\JetBrains\PyCharmCE2023.1\scratches\maincode.py
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\16787\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "C:\Users\16787\AppData\Roaming\JetBrains\PyCharmCE2023.1\scratches\maincode.py", line 12, in get_BMI
BMI = ((weightEntry * 703) // (heightEntry ** 2))
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

报错原因

移除int转换后,输入值是字符串类型,无法直接进行数学运算,必须转换为数字类型才能计算BMI。


最终修复方案

核心问题是变量覆盖和验证顺序错误,修复后的代码如下:

from tkinter import *
from tkinter.messagebox import *

def get_BMI():
    # 获取输入值,使用局部变量避免覆盖原Entry组件
    name = nameEntry.get().strip()
    height_str = heightEntry.get().strip()
    weight_str = weightEntry.get().strip()

    # 先检查是否有未填写的字段
    if not name or not height_str or not weight_str:
        showinfo(message='Error: 请填写所有必填字段')
        return

    # 验证并转换身高体重为整数,捕获转换异常
    try:
        height = int(height_str)
        weight = int(weight_str)
    except ValueError:
        showinfo(message='Error: 身高和体重必须是整数')
        return

    # 验证身高体重是否为正数
    if height <= 0 or weight <= 0:
        showinfo(message='Error: 身高和体重必须是正数')
        return

    # 计算BMI
    BMI = (weight * 703) // (height ** 2)
    showinfo(message=f'{name},你的BMI指数是 {BMI}。')

    # 清空输入框
    nameEntry.delete(0, END)
    heightEntry.delete(0, END)
    weightEntry.delete(0, END)

root = Tk()
root.title('BMI Calculator')

name = Label(root, text='输入你的姓名')
name.grid(row=1, column=0)
nameEntry = Entry(root)
nameEntry.grid(row=1, column=1)

height = Label(root, text='输入你的身高(英寸)')
height.grid(row=2, column=0)
heightEntry = Entry(root)
heightEntry.grid(row=2, column=1)

weight = Label(root, text='输入你的体重(磅)')
weight.grid(row=3, column=0)
weightEntry = Entry(root)
weightEntry.grid(row=3, column=1)

calculateBMI = Button(root, text='计算BMI', command=get_BMI)
calculateBMI.grid(row=4, column=1)

root.mainloop()

关键修改点

  1. 避免变量覆盖:使用局部变量存储输入值,不再覆盖全局的Entry组件对象,防止后续调用delete()方法时出错
  2. 调整验证顺序:先检查输入是否为空,再验证是否可转换为整数,最后验证是否为正数
  3. 异常处理:用try-except捕获字符串转整数的异常,比isdigit()更可靠(能处理负数、小数等不符合要求的输入)
  4. 代码可读性优化:移除不必要的全局变量,逻辑更清晰

内容的提问来源于stack exchange,提问作者n00bcoder_24

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 19:22:46