转换inpu时“ValueError:无法将字符串转换为浮点”

2024-05-15 21:51:46 发布

您现在位置:Python中文网/ 问答频道 /正文

最近我一直在处理一个代码,在这个错误上卡住了好几天。 基本上,这个程序计算出你每天要吃多少卡路里。我必须从一个条目中获取输入,我不知道如何将该输入(默认情况下是一个字符串)转换为浮点来开始使用数字。 我在Tkinter中使用Python3。

代码如下:

from tkinter import *

root = Tk()
root.geometry("1000x500")
root.resizable(FALSE, FALSE)
root.title("BMI Calculator")

def calc(args):

    def BMI_temp(args):
        print(str(boyage))
        BMI = IntVar()
        BMI = 66.5 + (13.75 * float(boykg)) + (5.003 * float(boycm)) - (6.755 * float(boyage))
        bmi_temp = Label(root, text="This is how many calories you have to eat if you have a non-active life: " + str(float(BMI)))
        bmi_temp.grid(row=3, sticky=W)

    def boy_age_fnct(args):
        boy_age_entry.focus_set()
        boy_cm_entry.delete(0, "end")
        boy_age.grid(row=2, sticky=W)
        boy_age_entry.grid(row=2, column=1)
        boy_age_entry.bind("<Return>", BMI_temp)

    def boy_cm_fnct(args):
        boy_cm_entry.focus_set()
        boy_kg_entry.delete(0, "end")
        boy_cm.grid(row=1, sticky=W)
        boy_cm_entry.grid(row=1, column=1)
        boy_cm_entry.bind("<Return>", boy_age_fnct)

    boy_kg_entry.focus_set()
    temp = boygirle.get()
    gender = temp.title()
    welcome.destroy()
    hello_lbl.destroy()
    boygirle.destroy()
    boygirlq.destroy()

    if gender[0] == 'B':
        boy_kg.grid(row=0, sticky=W)
        boy_kg_entry.grid(row=0, column=1)
        boy_kg_entry.bind("<Return>", boy_cm_fnct)

    boyage = boy_age_entry.get()
    boycm = boy_cm_entry.get()
    boykg = boy_kg_entry.get()

def hello(args):
    name_user = name_entry.get()
    name2 = name_user.title()
    name_entry.delete(0, "end")
    hello = "Hello " + name2 + "!"
    hello_lbl["text"] = hello
    hello_lbl.grid(row=2, sticky=W)
    btn_cont.grid(row=3, sticky=W)
    name.destroy()
    name_entry.destroy()
    btn_cont.focus_set()

def BMI():
    btn_cont.destroy()
    boygirlq.grid(row=3, sticky=W)
    boygirle.grid(row=3, column=0, ipadx=35)
    boygirle.bind("<Return>", calc)
    boygirle.focus_set()

welcome = Label(root, text="Hello! This is a BMR calculator. It tells you how many calories you have to eat!", font="System 14 bold")
name = Label(root, text="Please enter your name:", font="System 12")
hello_lbl = Label(root, font="System 14")
boygirlq = Label(root, text="Are you a boy or a girl?", font="System 12 bold")
boy_kg = Label(root, text="Please enter your weight(in kg):", font="System 12 bold")
boy_cm = Label(root, text="Please enter your height(in cm):", font="System 12")
boy_age = Label(root, text="Please enter your age(in years):", font="System 12")

btn_cont = Button(root, text="Continue", font="Helvetica 12", command=BMI, relief=RAISED)

boy_kg_entry = Entry(root, font="System 12", relief=SUNKEN)
boy_cm_entry = Entry(root, font="System 12", relief=SUNKEN)
boy_age_entry = Entry(root, font="System 12", relief=SUNKEN)
name_entry = Entry(root, font="System 12", relief=SUNKEN)
boygirle = Entry(root, font="System 12", relief=SUNKEN)
name_entry.bind("<Return>", hello)
name_entry.focus_set()

welcome.grid(row=0, columnspan=2, ipadx=200)
name.grid(row=1, sticky=W)
name_entry.grid(row=1, column=0)

root.mainloop()

我尝试了在网上找到的所有方法,但都没有成功。


Tags: textnameagecmrootsystemlabelgrid
1条回答
网友
1楼 · 发布于 2024-05-15 21:51:46

可能原因:您忘记填写一个字段

解释

一个float可以由str构造,它只需要有正确的格式。 您应该能够通过使用float(mystr)将看起来像浮点数的字符串转换为浮点数。

注意:

  • 无空格(或非数字字符)
  • 句点(.)作为十进制分隔符,而不是逗号(,)
  • 一些特殊的东西是允许的(例如“inf”,“5e3”, …)

很可能(如果没有从错误消息中删除任何内容),您忘记填写一个字段,因此正在尝试执行float('')

一些例子

>>> float('')  # probably your case
Traceback (most recent call last):
  File "<pyshell#74>", line 1, in <module>
    float('')
ValueError: could not convert string to float:
>>> float('1')
1.0
>>> float('1.0')
1.0
>>> float('no number')
Traceback (most recent call last):
  File "<pyshell#64>", line 1, in <module>
    float('no number')
ValueError: could not convert string to float: 'no number'
>>> float('10e30')
1e+31
>>> float('inf')
inf
>>> float('123.456')
123.456
>>> float('123,456')  # , not allowed
Traceback (most recent call last):
  File "<pyshell#68>", line 1, in <module>
    float('123,456')
ValueError: could not convert string to float: '123,456'
>>> float('123 456')  # no whitespace as separator
Traceback (most recent call last):
  File "<pyshell#69>", line 1, in <module>
    float('123 456')
ValueError: could not convert string to float: '123 456'

进一步的思考

获取浮点值的另一种方法是在弹出窗口中请求它们——这可以通过tkinter.simpledialog.askfloat完成。这将直接返回一个float,如果输入的字符串无法转换,则会显示一条错误消息。 但是,当用户单击“取消”按钮时,它也可能返回None,因此您可能希望在计算内容之前检查结果。

示例:

import tkinter as tk
from tkinter.simpledialog import askfloat

def click():
    val = askfloat('Title', 'The prompt:')  # float or None (cancel)
    if val is not None:
        tk.Label(root, text=f'The value "{val}" is a valid float').pack()  # f-string, replace with `'The value "{}" is ...'.format(val)` if you get an error (Python < 3.6)

root = tk.Tk()
tk.Button(root, text='Click!', command=click).pack()
root.mainloop()

编辑:

如果保留Entry小部件,则可能需要捕获错误并向用户显示消息。这很容易用tkinter.mesagebox来实现,特别是在这种情况下,showerror函数。

示例:

import tkinter as tk
from tkinter.messagebox import showerror

def click():
    try:
        val = float(entry.get())
    except ValueError as e:
        showerror('Error title', 'The number could not be converted to float:\n'+str(e))
    else:
        entry.delete(0, tk.END)
        Label(root, text=val).pack()

root = tk.Tk()
entry = tk.Entry(root)
tk.Label(root, text='insert a float value below:').pack()
entry.pack()
tk.Button(root, text='and click!', command=click).pack()
root.mainloop()

相关问题 更多 >