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()
应该希望将转换后的重量输出到三个单独的框中。
解决方案
您没有提供输入,但您的错误表明第一个字段为空。如果您填写所有 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))
推荐阅读
- ruby-on-rails - 附件控制器中的名称错误#indicateur
- msbuild - 部署服务结构 Visual Studio 构建失败
- mysql - 设计用于存储书籍、版本、颜色的表格布局
- redux - 是否可以通过 redux 存储在兄弟组件之间共享承诺?
- json - Springboot - 空获取休息响应
- gulp - 每次我运行 gulp 任何东西时,我都会收到一个断言错误。- 必须指定任务功能
- asp.net - IIS 在 ASP.NET 核心 NOPCommerce 的子文件夹中部署 php 应用程序
- c# - 只能在 DependencyObject 的 DependencyProperty 上设置绑定?
- c# - 查询存储为 XML 的字符串属性
- javascript - JavaScript:获取对象的属性值