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, but int('')
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
-except
in a get_value
function:
def get_value(entryWidget):
value = entryWidget.get()
try:
return int(value)
except ValueError:
return None
Then, instead of setting lambda: print(e.get())
as a callback to your button, pass lambda: print(get_value(e))
.
If the value could be parsed as an integer, this will print the result of int(e.get())
.
If it couldn't, this will print None
.
Here is the modified version of your code:
import tkinter
root= tkinter.Tk()
def get_value(entryWidget):
value = entryWidget.get()
try:
return int(value)
except ValueError:
return None
e = tkinter.Entry(root)
e.pack()
b = tkinter.Button(root, command=lambda: print(e.get()))
b.pack()
conversion = get_value(e)
if conversion is not None:
conversion *= 1.8 + 32
l = tkinter.Label(root, text=conversion)
top.mainloop()
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:
import tkinter
def get_value(entryWidget):
value = entryWidget.get()
try:
return int(value)
except ValueError:
return None
def convert(value):
if value is None:
return None
else:
return 1.8*value + 32
def set_label_text(label, entry):
value = convert(get_value(entry))
if value is None:
label['text'] = "Enter an integer"
else:
label['text'] = value
root = tkinter.Tk()
e = tkinter.Entry(root)
l = tkinter.Label(root, text="")
b = tkinter.Button(root, text="Convert", command=lambda: set_label_text(l, e))
e.pack()
l.pack()
b.pack()
root.mainloop()