Search code examples
pythonpython-3.xtkinter

How to get an integer from a tkinter entry box?


I am trying to work out how to get a value from a tkinter entry box, and then store it as a integer. This is what I have:

AnswerVar = IntVar()
AnswerBox = Entry(topFrame)
AdditionQuestionLeftSide = random.randint(0, 10)
AdditionQuestionRightSide = random.randint(0, 10)
AdditionQuestionRightSide = Label(topFrame, text= AdditionQuestionRightSide).grid(row=0,column=0)
AdditionSign = Label(topFrame, text="+").grid(row=0,column=1)
AdditionQuestionLeftSide= Label(topFrame, text= AdditionQuestionLeftSide).grid(row=0,column=2)
EqualsSign = Label(topFrame, text="=").grid(row=0,column=3)
AnswerBox.grid(row=0,column=4)
answerVar = AnswerBox.get()
    
root.mainloop() 
(


)

How can I take the input from AnswerBox, and store it in the integer variable "answer"?


Solution

  • Since you have an IntVar associated with the entry widget, all you need to do is get the value of that object with the get method:

    int_answer = answer.get()
    

    If you don't use an IntVar, you can get the value of the entry widget and the convert it to an integer with int:

    string_answer = AnswerBox.get()
    int_answer = int(string_answer)