0

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

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
Sam
  • 3
  • 2
  • You could use a tk.IntVar as a container for your entry widget. That will make it so anytime you `.get()` the IntVar, it will return an integer. However it does not restrict the user from entering non-ints into the field. If you need to validate this field/restrict certain keys then I recommend looking at this Q/A: https://stackoverflow.com/a/8960839/3308951 – SyntaxVoid Jul 30 '19 at 18:49
  • Thank you @ SyntaxVoid I finally got it working using what you said! – Sam Jul 31 '19 at 02:42
  • You are calling `t.get()` about a millisecond after creating the UI, well before the user even sees the UI, much less type something. – Bryan Oakley Aug 01 '19 at 04:37

2 Answers2

0

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.

Alexander Santos
  • 1,458
  • 11
  • 22
-1

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)
  • While this makes the error go away, it's still not a proper solution as `stringT` will always be empty since `t.get()` is being called before the window is displayed on the screen. – Bryan Oakley Aug 01 '19 at 04:38