I am coding a simple program which converts imperial units into metric units. However, when I use an Entry.get() command, I need to convert it to an integer and when I try to do that
I get this error:
Traceback (most recent call last):
File "C:/Users/Bill/converter.py", line 18, in <module>
conversion=int(e.get())
ValueError: invalid literal for int() with base 10: ''
I tried running an extremely basic version of what I was doing (which is written below), but that still caused the same error.
import tkinter
root= tkinter.Tk()
e=tkinter.Entry(root)
e.pack()
b=tkinter.Button(root, command= lambda: print(e.get()))
b.pack()
conversion=int(e.get())
conversion= conversion* 1.8 +32
l = tkinter.Label(root, text=conversion)
top.mainloop()
I only recently started coding again, so the answer is probably something really simple that I missed, but thanks for any answers.
The problem, and what the error states, is that the empty string
''cannot be converted to an integer.In fact, a lot of strings cannot be converted to an integer. In your case,
int(e.get())raises an error because the entry is empty, butint('')raises an error. Therefore, you need to validate your input before converting it, so as to process it only when it contains the string representation of an integer.You can wrap a
try-exceptin aget_valuefunction:Then, instead of setting
lambda: print(e.get())as a callback to your button, passlambda: print(get_value(e)). If the value could be parsed as an integer, this will print the result ofint(e.get()). If it couldn't, this will printNone.Here is the modified version of your code:
This, however, is a bit awkward. Since the content of the entry is caught before the main loop, the latter will always be empty.
When dealing with GUIs, you cannot think sequencially as you usually do. You should rather ask your button to update the content of your label when pressed, so as to have it display the result of the conversion: