首页 > 解决方案 > 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

标签: pythontkinter

解决方案


最初执行代码时直接调用该函数,当输入框为空时,其中没有任何内容,因此您必须将其删除并从按钮中调用该函数,并添加 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()

推荐阅读