'tkinter: How to avoid this ValueError: could not convert string to float: ''?

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()

I am trying to make a pound to kilogram converter and basically this gives me the error:

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


Solution 1:[1]

The function is being called directly when the code is being executed initially, when the entry box is empty, there is nothing inside of it, so you have to remove that and just call the function from the buttons, and also add try and except if you want to prevent entry of anything other than numbers:

from tkinter import *

root = Tk()

entry = Entry(root, width=50)
entry.grid(row=1, column=0)

def ButtonClick():
    userInput = entry.get() 
    try: # If it is float then do the following
        kilograms = float(userInput)/2.2 
    except ValueError: # If it is not a number, then stop the function
        return
    
    entryLabel.config(text=kilograms) # Update the label with the new value

answerButton = Button(root, text="Convert!", command=ButtonClick)
answerButton.grid(row=2, column=0)

entryLabel = Label(root) # Create the label initially, so we can update it later
entryLabel.grid(row=3, column=0)

root.mainloop()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1