Search code examples
pythontkintertkinter-entry

Compare tkinter Entry to actual addition answer


I'm trying to compare the input of an Entry box to the actual answer. This is one of my first python projects and I'm still very confused and to be honest I don't even know how to start asking the question.

The user will click either the addition or subtraction button. A string will appear asking "What does 4 + 5 equal?" The numbers are generated randomly.

I then insert an Entry box using the tkinter library. I don't know how to get() the input and compare it to the sum or difference of the actual numbers.

I was trying to follow this video but I've failed using other methods as well. FYI, I was focusing on the addition method mostly so if you test, that with addition first.

from tkinter import Entry
import tkinter as tk
import random as rand

root = tk.Tk()
root.geometry("450x450+500+300")
root.title("Let's play Math!")

welcomeLabel = tk.Label(text="LET'S PLAY MATH!").pack()
startLabel = tk.Label(text='Select a math operation to start').pack()

def addition():
    a = rand.randrange(1,10,1)
    b = rand.randrange(1,10,1)
    global Answer
    Answer = a + b

    tk.Label(text="What does " + str(a) + " + " + str(b) + " equal? ").place(x=0, y=125)
    global myAnswer
    myAnswer = Entry().place(x=300, y= 125)

def checkAnswer():
    entry = myAnswer.get()

    while int(entry) != Answer:
        if int(entry) != Answer:
            tk.Label(text="Let's try again.").pack()
        elif int(entry) == Answer:
            tk.Label(text="Hooray!").pack()


addBtn = tk.Button(text="Addition", command=addition).place(x=100, y = 60)
subBtn = tk.Button(text="Subtraction", command=subtraction).place(x=200, y=60)
checkBtn = tk.Button(text="Check Answer", command=checkAnswer).place(x=300, y = 150)

tk.mainloop()

Solution

  • All you need to do to fix your issue is separate the creation of your Entry() object from the placing of it:

    def addition():
        a = rand.randrange(1,10,1)
        b = rand.randrange(1,10,1)
        global Answer
        Answer = int(a + b)
    
        tk.Label(text="What does " + str(a) + " + " + str(b) + " equal? ").place(x=0, y=125)
        global myAnswer
        myAnswer = Entry()
        myAnswer.place(x=300, y= 125)
    

    Entry() returns the entry object, which has a get() method. However, when you chain .place(), you return its result instead, which is None. Therefore you never actually store the Entry object in your variable.

    Also, it is a good idea to ensure that Answer is an int as well.