简体   繁体   中英

How can i get rid of this traceback error: ValueError: invalid literal for int() with base 10: ''

Thanks to SyntaxVoid in the comments I solved this problem.

I created an Entry in tkinter for a timer and I want that input to be the variable for how long to set the timer. I need this variable to be an integer instead of a string, but I get this error.

I have seen some posts about this and they all said to make a variable and use get() and then make that variable an int but this didn't work as you can see.

I believe that this is all the code from the error:

t = Entry()
t.pack()
stringT = t.get()
intT = int(stringT)

The error:

Traceback (most recent call last):
  File "C:\Users\Traner\Desktop\Python Files\Scoreboard GUI\scoreboard.py", line 41, in <module>
    intT = int(stringT)
ValueError: invalid literal for int() with base 10: ''

I am hoping to get the Entry() to be an integer instead of a string

You can do something like this:

try:
    intT = int(stringT)
except ValueError:
    intT = 0 # Do something

In this case, if it cannot be converted, it will be considered 0. Check if that is applicable for your software.

Basically, what it does is when the exception is raised, catch and do something.

TIP: You may also want to use something like isdigit() to check if what you received isn't, for example, a word...

EDIT: As @Carcigenicate said in comments:

intT = int(stringT) if stringT else 0

This could also do the thing, in a more pythonic way. But this would fail if stringT is written as non-digit (For example, "abcd"). You should still validate it.

In the code that you have above, stringT returns an empty string, and therefore you get the exception.

Try:

t = Entry()
t.pack()
stringT = t.get()
if stringT:
    intT = int(stringT)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM