0

I'm writing a basic number guessing game, and I'm trying to put the program into a window. Everything works fine except when I try to access the variable created in my entry_box and then compare it to an int.

Right now, the variable coming out of the entry_box is a StringVar. How do I convert this to an integer so I can compare the variables?

# Creates the entry box and variable that will be used in it
# answer = StringVar()
entry_box = Entry(window, textvariable = answer, width = 25, bg = 'white') .place(x = 350, y = 0)

num1 = answer.get()

So right now answer is a StringVar, and im trying to convert it to an Integer. Any help would be appreciated.

ndmeiri
  • 4,979
  • 12
  • 37
  • 45
Kirby127
  • 39
  • 1
  • 1
  • 10

2 Answers2

0

The easiest way to do this is the same way you convert any string to an integer in Python:

num1 = answer.get() # now we have a str
num2 = int(num1) # now we have an int

Of course if the user typed something like spam in the Entry—or nothing at all—that second line is going to raise a ValueError. You have to decide how you want to handle that.

(For a fancier project, you might want to consider using an IntVar instead of a StringVar and/or using manual Tkinter validation, but for a simple exercise, you probably don't need that.)

abarnert
  • 354,177
  • 51
  • 601
  • 671
0

You just use int():

num1 = int(answer.get())
SergiyKolesnikov
  • 7,369
  • 2
  • 26
  • 47