The code is essentially a math quiz that asks the user to input an answer. The code will then display if the answer is right or wrong. However, currently the self.feedback.configure(text = "Correct") is not being run in the method "Next" if the self.feedback.configure(text = "") is inserted into the "Check" method (there is a 0.2 second delay so the code should configure to "Correct" for 0.2 seconds before configuring back to "" an empty string)
This is the code:
from tkinter import *
from tkinter import ttk
import random
import time
class TimesTable:
def __init__(self, parent):
""" Sets up the GUI.
"""
self.points = 0
self.problem_label = ttk.Label(parent, text = "Question:") #empty for now
self.problem_label.grid(row = 0, column=0, sticky = W, padx = 10, pady = 10)
self.answer_entry = ttk.Entry(parent, width = 7)
self.check_btn = ttk.Button(parent, text = "Check Answer", command = self.Check)
self.next_btn = ttk.Button(parent, text = "Start", command = self.Next)
self.next_btn.grid(row = 0, column = 1, sticky = W, padx = 10, pady = 10)
self.feedback = ttk.Label(parent, text = "Click 'Start' to begin!")
self.feedback.grid(row = 1, column = 0, sticky = W, padx = 10, pady = 10)
def Next(self):
time.sleep(0.2)
***self.feedback.configure(text = "")*** #Fix this (taking it out makes the .configure in Check work)
number1 = random.randrange(2,10)
number2 = random.randrange(2,10)
operation = ["*", "+", "-"]
operation_ran = operation[(random.randrange((len(operation))))]
display_question = "Question: {} {} {} = ".format(number1, operation_ran, number2)
self.ans = eval("{} {} {} ".format(number1, operation_ran, number2))
self.problem_label.configure(text = display_question)
self.check_btn.grid(row = 1, column = 1, sticky = W, padx = 10, pady = 10)
self.answer_entry.grid(row = 0, column = 1, sticky = W, padx = 10, pady = 10)
self.next_btn.grid_remove()
def Check(self):
try:
if int(self.answer_entry.get()) == int(self.ans):
***self.feedback.configure(text = "Correct!")*** #Why does this not work? in def Next, it is configured to nothing but shouln't it still sleep for 0.2s before configuring to nothing via the calling of method def Next???
self.points += 1
self.answer_entry.delete(0,END)
self.answer_entry.focus()
print(self.points) #Just to check point system works
self.Next()
else:
***self.feedback.configure(text = "Wrong. The answer is {}".format(self.ans))***
if self.points > 0:
self.points -= 1
self.answer_entry.delete(0,END)
self.answer_entry.focus()
print(self.points)
self.Next()
except ValueError:
self.feedback.configure(text = "Please enter a valid number")
self.answer_entry.delete(0,END)
self.answer_entry.focus()
#main routine
if __name__ == "__main__":
root = Tk()
root.title("Math Quiz")
tester = TimesTable(root)
root.mainloop()