首页 > 解决方案 > 无法从 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()

应该希望将转换后的重量输出到三个单独的框中。

标签: python-3.xtkinter

解决方案


您没有提供输入,但您的错误表明第一个字段为空。如果您填写所有 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被击中时 - 您尝试将所有三个输入字段转换为浮动,无论是否有人在那里输入。你得到一个错误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))

推荐阅读