I'm in the process of creating a budget app and I'm running into a ValueError: invalid literal for int() with base 10: ''
. I know a lot of you guys are probably going to comment that this thread has been answered already but not in my case. I know that I can not convert empty string data to an integer but when it comes to entry boxes on Tkinter. In this case, the value will be imputed by the user but in the meantime, the boxes are empty until the user inputs a response. At one point in time, the code worked when
month_amount
was a local variable.
I then tried to make it a global variable then I got this error. Then when I switched it back to being a local variable inside the calculate()
function it gave me the same error. My biggest question is what is the workaround I can do to convert the entry box responses into int()
data?
I've added a snippet of the code below.
Month_entry = tk.Entry(root, font=('Arial', 12, "bold"))
Month_entry.grid(row=5, column=1, columnspan=1)
Month_entry.configure(width=68)
Month_entry.place(x=0, y=120)
def calculate():
month_amount = int(Month_entry.get())
ValueError: invalid literal for int() with base 10: ''
There is no workaround necessary, you just need to use standard best practices. In your case, you either need to detect an empty string, or catch the error when trying to convert the empty string, or both.
For example, if you want to report the error to the user, define a function for doing that and then catch the error:
Month_entry = tk.Entry(root, font=('Arial', 12, "bold"))
...
def calculate():
month = Month_entry.get()
try:
month_amount = int(month)
except ValueError:
report_error(f"month ('{month}') is not a valid number")
Another solution might be to set the month to a default value if the user hasn't entered anything:
def calculate():
month = Month_entry.get()
if month == "":
month = 0
else:
month = int(month)
Or, you might want to combine the two, so that you can gracefully handle an empty string while still catching errors.
Arguably, the best solution is for you to be validating the data as the user types, and only enable a button that calls the calculate
function if all of the inputs have valid data.
For an example of how to do entry validation, see Interactively validating Entry widget content in tkinter