python - tkinter:如何避免此“ValueError:无法将字符串转换为浮点数:”?
问题描述
from tkinter import *
root = Tk()
entry = Entry(root, width=50)
entry.grid()
entry.grid(row=1,column=0)
def ButtonClick():
userInput = entry.get()
entryLabel = Label(root, text=userInput)
entryLabel.grid()
kilograms = float(userInput)/2.2
answerButton = Button(root, text="Convert!", command=ButtonClick)
answerButton.grid(row=2,column=0)
ButtonClick()
root.mainloop()
我正在尝试制作磅到千克的转换器,基本上这给了我错误:
Traceback (most recent call last):
File "main.py", line 25, in <module>
ButtonClick()
File "main.py", line 15, in ButtonClick
kilograms = float(userInput)/2.2
ValueError: could not convert string to float: ''
Process finished with exit code 1
解决方案
最初执行代码时直接调用该函数,当输入框为空时,其中没有任何内容,因此您必须将其删除并从按钮中调用该函数,并添加 try 和 except if您想防止输入除数字以外的任何内容:
from tkinter import *
root = Tk()
entry = Entry(root, width=50)
entry.grid()
entry.grid(row=1, column=0)
def ButtonClick():
try: #if it is number then do the following
userInput = entry.get()
kilograms = float(userInput)/2.2
entryLabel = Label(root, text=userInput)
entryLabel.grid()
print(kilograms)
except ValueError: #if it is not a number, then dont do anything
pass
answerButton = Button(root, text="Convert!", command=ButtonClick)
answerButton.grid(row=2, column=0)
root.mainloop()
推荐阅读
- android - “清单合并失败并出现多个错误,请参阅日志”错误
- java - Gson如何将已知大小的列表转换为多个字段
- python - 来自 Django 模型的表单中的自定义选择框字段
- gun - 如何触发 .on()
- javascript - html中的图像在页面中无法正确显示
- python - 在具有第二个数据帧行条件的数据帧中添加计数行
- http - 将 mor 信息添加到颤振选项卡
- html - 使用模型中的值,或者如果它未定义,则使用默认值
- java - getInputStream() 和 getOutputStream() 的 python 等价物是什么?
- python - 检查值是否高于阈值,如果是,则替换为