无法将字符串从tkinter字段转换为float

时间:2019-01-11 10:56:12

标签: python-3.x tkinter

继续弹出

File "script1.py", line 6, in conversion
    weight = float(e1_value.get()) * 1000
ValueError: could not convert string to float:

当我运行代码时,有什么想法吗?

找不到任何空格或任何东西告诉我为什么它不能转换输入。

from tkinter import *

window = Tk()

def conversion():
    weight = float(e1_value.get()) * 1000
    weight = float(e2_value.get()) * 2.20462
    weight = float(e3_value.get()) * 35.274
    t1.insert(END,weight)


e1_value = StringVar()
e1 = Entry(window, textvariable = e1_value)
e1.grid(row = 1, column = 0)

e2_value = StringVar()
e2 = Entry(window, textvariable = e2_value)
e2.grid(row = 1, column = 1)

e3_value = StringVar()
e3 = Entry(window, textvariable = e3_value)
e3.grid(row = 1, column = 2)

b1 = Button(window, text = 'Convert', command = conversion)
b1.grid(row = 0, column = 2)

t1 = Text(window, height = 1, width = 20)
t1.grid(row = 0, column = 1)

window.mainloop()

希望将转换后的重量输出到三个单独的盒子中。

1 个答案:

答案 0 :(得分:0)

您没有提供输入,但是您的错误表明第一个字段为空。如果您填写所有3个输入,您的代码就可以正常工作。问题是你

def conversion():
    weight = float(e1_value.get()) * 1000
    weight = float(e2_value.get()) * 2.20462
    weight = float(e3_value.get()) * 35.274
    t1.insert(END,weight)

因此,当击中convert时,您将尝试将所有三个输入字段都转换为float,而不管是否有人在其中输入。您在e1上遇到一个错误-用数字填写该错误,并在e2上得到一个错误,然后填写,并且-您猜对了-您在e3上遇到了错误。一种可能的解决方法:

from tkinter import messagebox  
def conversion():
    try:
        weight = float(e1_value.get()) * 1000
        weight = float(e2_value.get()) * 2.20462
        weight = float(e3_value.get()) * 35.274
        t1.insert(END,weight)
    except ValueError:
        messagebox.showerror("What the hell?","Please type a valid number in all three fields!")
    except Exception as e:
        messagebox.showerror("Oh no!","Got some other weird error:\n"+str(e))