“ValueError:无法将字符串转换为浮点数";转换输入时 [英] "ValueError: could not convert string to float" when converting input

查看:43
本文介绍了“ValueError:无法将字符串转换为浮点数";转换输入时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我一直在编写代码,但被这个错误卡住了好几天.基本上,该程序会计算您每天必须摄入多少卡路里.我必须从条目中获取输入,但我不知道如何将该输入(默认为字符串)转换为浮点数以开始使用数字.我在 Tkinter 中使用 Python 3.

代码如下:

from tkinter import *根 = Tk()root.geometry("1000x500")root.resizable(假,假)root.title("BMI 计算器")定义计算(参数):def BMI_temp(args):打印(str(boyage))BMI = IntVar()BMI = 66.5 + (13.75 * float(boykg)) + (5.003 * float(boycm)) - (6.755 * float(boyage))bmi_temp = Label(root, text="如果你没有活跃的生活,你需要吃多少卡路里:" + 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("<返回>", 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(行=1,列=1)boy_cm_entry.bind("<返回>", boy_age_fnct)boy_kg_entry.focus_set()temp = boygirle.get()性别 = temp.title()欢迎.销毁()hello_lbl.destroy()boygirle.destroy()boygirlq.destroy()如果性别[0] == 'B':boy_kg.grid(row=0,sticky=W)boy_kg_entry.grid(row=0, column=1)boy_kg_entry.bind("<返回>", boy_cm_fnct)boyage = boy_age_entry.get()boycm = boy_cm_entry.get()boykg = boy_kg_entry.get()定义你好(参数):name_user = name_entry.get()name2 = name_user.title()name_entry.delete(0, "end")你好 = "你好 " + name2 + "!"hello_lbl["text"] = 你好hello_lbl.grid(row=2,sticky=W)btn_cont.grid(row=3,sticky=W)名称.销毁()name_entry.destroy()btn_cont.focus_set()定义 BMI():btn_cont.destroy()boygirlq.grid(row=3,sticky=W)boygirle.grid(row=3, column=0, ipadx=35)boygirle.bind("<返回>", calc)boygirle.focus_set()Welcome = Label(root, text="Hello! 这是一个 BMR 计算器.它告诉你你需要吃多少卡路里!", font="System 14 bold")name = Label(root, text="请输入您的姓名:", font="System 12")hello_lbl = Label(root, font="System 14")boygirlq = Label(root, text="你是男孩还是女孩?", font="System 12 bold")boy_kg = Label(root, text="请输入您的体重(公斤):", font="System 12 粗体")boy_cm = Label(root, text="请输入您的身高(cm):", font="System 12")boy_age = Label(root, text="请输入您的年龄(岁):", font="System 12")btn_cont = Button(root, text="Continue", font="Helvetica 12", command=BMI,救济=RAISED)boy_kg_entry = Entry(root, font="System 12", Relief=SUNKEN)boy_cm_entry = Entry(root, font="System 12", 浮雕=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("<返回>", 你好)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()

我尝试了在互联网上找到的所有方法,但没有任何效果.

解决方案

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

说明

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

注意:

  • 没有空格(或非数字字符)
  • 句点 (.) 作为小数点分隔符,而不是逗号 (,)
  • 一些特殊的东西是允许的(例如inf5e3、...)

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

一些例子

<预><代码>>>>float('') # 可能是你的情况回溯(最近一次调用最后一次):文件<pyshell#74>",第 1 行,在 <module> 中.漂浮('')ValueError: 无法将字符串转换为浮点数:>>>浮动('1')1.0>>>浮动('1.0')1.0>>>float('没有数字')回溯(最近一次调用最后一次):文件<pyshell#64>",第 1 行,在 <module> 中.float('没有数字')ValueError: 无法将字符串转换为浮点数:'无数字'>>>浮动('10e30')1e+31>>>浮动('inf')信息>>>浮动('123.456')123.456>>>float('123,456') # , 不允许回溯(最近一次调用最后一次):文件<pyshell#68>",第 1 行,在 <module> 中.浮动('123,456')ValueError: 无法将字符串转换为浮点数:'123,456'>>>float('123 456') # 没有空格作为分隔符回溯(最近一次调用最后一次):文件<pyshell#69>",第 1 行,在 <module> 中.浮动('123 456')ValueError: 无法将字符串转换为浮点数:'123 456'

进一步的想法

获取浮点值的另一种方法是在弹出窗口中询问它们——这可以通过 tkinter.simpledialog.askfloat 来完成.如果输入的字符串无法转换,这将直接返回一个 float 并显示错误消息.但是,当用户点击取消"按钮时,它也可能返回None.按钮,所以你可能想在计算之前检查结果.

示例:

导入 tkinter 作为 tk从 tkinter.simpledialog 导入 askfloat定义点击():val = askfloat('Title', 'The prompt:') # float 或 None (取消)如果 val 不是 None:tk.Label(root, text=f'The value "{val}" is a valid float').pack() # f-string, 替换为 `'The value "{}";是 ...'.format(val)` 如果出现错误(Python < 3.6)根 = tk.Tk()tk.Button(root, text='Click!', command=click).pack()root.mainloop()

如果您保留 Entry 小部件,您可能希望捕获错误并向用户显示一条消息.这可以通过 tkinter.mesagebox 轻松完成,特别是在这种情况下,showerror 函数.

示例:

导入 tkinter 作为 tk从 tkinter.messagebox 导入 showerror定义点击():尝试:val = float(entry.get())除了 ValueError 作为 e:showerror('错误标题', '数字无法转换为浮点数:\n'+str(e))别的:entry.delete(0, tk.END)标签(根,文本= val).包()根 = tk.Tk()entry = tk.Entry(root)tk.Label(root, text='在下面插入一个浮点值:').pack()entry.pack()tk.Button(root, text='and click!', command=click).pack()root.mainloop()

Recently I have been working on a code and got stuck for days on this error. Basically the program calculates how many calories you have to eat everyday. I have to take input from an entry and I don't know how to convert that input(it's a string by default) into a float to start using the numbers. I am using Python 3 with Tkinter.

Here is the code:

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()

I tried all the methods I found on the internet but nothing worked.

解决方案

Probable cause: you forgot to fill out one field

Explanation

a float can be constructed from a str, it just has to have the right format. You should be able to convert strings that look like floats to floats by just using float(mystr).

Pay attention to:

  • No spaces (or non-digit characters)
  • Period (.) as decimal separator, not comma (,)
  • some special things are allowed (e.g. inf, 5e3, ...)

Most probably (if you didn't cut anything off your error message), you forgot to fill out one field and are thus trying to perform float('').

Some examples

>>> 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'

Further thoughts

An alternative for getting the float values is asking for them in a popup window -- this can be done with tkinter.simpledialog.askfloat. This will return you a float directly and show an error message if the string entered could not be converted. But, it may also return None when the user clicks the "Cancel" button, so you might want to check the result before computing stuff.

Example:

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()

Edit:

If you keep the Entry widgets, you may want to catch the error and show the user a message. This can easily be done with tkinter.mesagebox, specifically of this case the showerror function.

Example:

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()

这篇关于“ValueError:无法将字符串转换为浮点数";转换输入时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆