Skip to content
Advertisement

python tkinter “in” operator doesn’t work

my problem is the programme won’t state the answer as correct only if you put the answer alone, but i want to make that you can actually put a phrase in the entry widget and if the answer is in that phrase it would say correct, i made this work without tkinter but i canno’t make it work in tkinter here is my code, could you please help, thanks.

the code

import tkinter as tk
from time import sleep

win = tk.Tk()

win.title("Learning game")

class Question:
    def __init__(self,prompt,answer):
        self.answer = answer
        self.prompt = prompt

score = 0



def ask():
    global questions
    global useranwser
    global score
    if questions:
            #Check both the possible answers
        if useranwser.get() in questions[0].answer:
            print("Correct")
            score += 1
        else:
            print("Incorrect")
        questions.pop(0)
        if questions:
            s.set(questions[0].prompt) 
        else:
            print('Done')
            print("Your score is : ",score)
            quit() #optional
        useranwser.set('')


question_prompts = [
    "When did Tunisia gain independence? n 1956 , 1984  , 1965 n", "What is the captial of tunis ? n Tunis, Gafsa, Nabuel n",
    "Who won 2018 football world cup ? n Italy, France, England n","how long is the eiffel tower ?n 324m, 354m, 412m n",
    "What is the heaviest metal n Iron, Copper, Uraniam n "
]

questions = [
    Question(question_prompts[4], "uraniam"),
    Question(question_prompts[0], "1956"),
    Question(question_prompts[1], "tunis"),
    Question(question_prompts[2], "france"),
    Question(question_prompts[3], "324m")
]

s = tk.StringVar()
useranwser = tk.StringVar() 
q = tk.Label(win,textvariable = s)
q.grid(row = 0, column = 0)
u_answer = tk.Entry(win, textvariable = useranwser)
u_answer.grid(row = 1, column = 0)
b = tk.Button(win, text ="Submit", command = ask)
b.grid(row = 2, column =0 )
s.set(questions[0].prompt)#Set the initial question 

 

win.mainloop()

Advertisement

Answer

I had to flip this if statment from this :

if useranwser.get() in questions[0].answer:
            print("Correct")
            score += 1

to this:

if questions[0].answer in useranwser.get():
            print("Correct")
            score += 1

Thanks to @justin ezequiel for the solution and @random davis for a debugging tip

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement