JavaScript
x
24
24
1
from tkinter import *
2
3
root = Tk()
4
5
entry = Entry(root, width=50)
6
entry.grid()
7
entry.grid(row=1,column=0)
8
9
def ButtonClick():
10
11
userInput = entry.get()
12
entryLabel = Label(root, text=userInput)
13
entryLabel.grid()
14
15
kilograms = float(userInput)/2.2
16
17
answerButton = Button(root, text="Convert!", command=ButtonClick)
18
answerButton.grid(row=2,column=0)
19
20
21
ButtonClick()
22
23
root.mainloop()
24
I am trying to make a pound to kilogram converter and basically this gives me the error:
JavaScript
1
9
1
Traceback (most recent call last):
2
File "main.py", line 25, in <module>
3
ButtonClick()
4
File "main.py", line 15, in ButtonClick
5
kilograms = float(userInput)/2.2
6
ValueError: could not convert string to float: ''
7
8
Process finished with exit code 1
9
Advertisement
Answer
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:
JavaScript
1
24
24
1
from tkinter import *
2
3
root = Tk()
4
5
entry = Entry(root, width=50)
6
entry.grid(row=1, column=0)
7
8
def ButtonClick():
9
userInput = entry.get()
10
try: # If it is float then do the following
11
kilograms = float(userInput)/2.2
12
except ValueError: # If it is not a number, then stop the function
13
return
14
15
entryLabel.config(text=kilograms) # Update the label with the new value
16
17
answerButton = Button(root, text="Convert!", command=ButtonClick)
18
answerButton.grid(row=2, column=0)
19
20
entryLabel = Label(root) # Create the label initially, so we can update it later
21
entryLabel.grid(row=3, column=0)
22
23
root.mainloop()
24