python tkinter代码提问

请问大家这里如何将字符串类型转为浮点型进行数学计算而不被报错?

img


import tkinter as tk
from tkinter import *
from tkinter import messagebox
root=tk.Tk()
root.geometry('+700+200')
root.title('登录')
name=tk.StringVar()
password=tk.StringVar()
Label(root,text='用户名',width=6).place(x=1,y=21)
Entry(root,width=20,textvariable=name).place(x=45,y=21)
Label(root,text='密码',width=6).place(x=1,y=55)
Entry(root,width=20,show='*',textvariable=password).place(x=45,y=55)
def then():
import tkinter as tk
from tkinter import messagebox
root=tk.Tk()
root.geometry('+700+200')
root.title('BMI')
shengao=tk.StringVar()
tizhong=tk.StringVar()
Label(root,text='身高(m)',width=6).place(x=1,y=21)
Entry(root,width=20,textvariable=shengao).place(x=50,y=21)
Label(root,text='体重(kg)',width=6).place(x=1,y=55)
Entry(root,width=20,textvariable=tizhong).place(x=50,y=55)
Label(root,text='性别',width=6).place(x=1,y=89)
Radiobutton(root,text='男性',value=1).place(x=60,y=89)
Radiobutton(root,text='女性',value=0).place(x=128,y=89)
Label(root,text='正常人的BMI是18.5%-23.9%',width=25,foreground='red').place(x=10,y=120)
def lg():
sg=shengao.get()
tz=tizhong.get()
Button(root,text='计算',width=8,command=lg).place(x=25,y=150)
Button(root,text='取消',width=8,command=quit).place(x=110,y=150)
root.mainloop()
def login():
nm=name.get()
pw=password.get()
if nm=='202131216082' and pw=='2022':
then()
else:
messagebox.showwarning(title='警告',message='登陆失败,请检查账号密码')
Button(root,text='登录',width=8,command=login).place(x=25,y=140)
Button(root,text='取消',width=8,command=quit).place(x=110,y=140)
root.mainloop()

你字符串中是什么内容?
字符串是是不是有数字之外字符,所以不能转为浮点数

你在float 上面加一句print ,看看是个啥?

在你的

sg=shengao.get()

后面加一条输出,查看下输出类型:

print(sg)
print(type(sg))

知道输出之后才好做下一步判断


如果输出是空白,那么说明你的这个数据根本没有获取到,所有输出为空字符串,不能转换为浮点数

代码修改成这个试下

try:
    sg = shengao.get()
    print("sg", sg)
    print("type", type(sg))
    sg=float(sg)
except Exception as e:
    sg = shengao.get()
    print("无法转换为浮点数,报错为:", str(e))

如有问题及时沟通