So I'm trying to help a student figure out how to create a simple quiz by reading from a text file with the questions, options, and answers. He wants to use guizero instead of the simple built-in input() and print() functions.
I would like him to avoid creating a separate check function for each question, but I don't have much experience with guizero. I've been reading the manual pages, and the below code approximates what we are trying to accomplish but doesn't work because selected_value
is not defined until after the program runs. Am I approaching this the wrong way?
from guizero import App, Text, ButtonGroup
app = App(title="Quiz Test", height=800, width=600)
def check_answer(selected_value, answer):
if selected_value == answer:
result.value = "Correct"
else:
result.value = "Wrong"
question_data = []
data_file = open("quiz_ques.txt", 'r')
for line in data_file.read().splitlines():
question_data = line.split(", ")
question_data.reverse() ; question = question_data.pop()
question_data.reverse() ; answer = question_data.pop()
q_options = question_data
text = Text(app, text=question)
choice = ButtonGroup(app, options=q_options, selected=1, command=check_answer, args=[selected_value, answer])
result = Text(app)
data_file.close()
app.display()
CodePudding user response:
try changing
command=check_answer()
to
command=check_answer
in the original version you were calling check_answer()
as soon as you defined your program... in the second version it will not be called until the button is clicked
CodePudding user response:
I figured this out using a couple of lists for anyone looking for a solution. Someone who is more of a python expert could probably simplify this, using some pythonic idiom, built-in functions, or standard modules, but this solution works even if it's a bit of a hack. Improvements on this are welcomed. :)
from guizero import App, Text, ButtonGroup
app = App(title="Quiz Test", height=800, width=600)
def check_answer(answer, result, cnt):
if choices[cnt].value == answer:
result.text_color = 'green'
result.value = "Correct"
update_score()
else:
result.text_color = 'red'
result.value = "Wrong"
update_score()
def update_score():
score = 0
for result in results:
if result.value == "Correct":
score = 1
score_txt.value = "Score: " str(score)
question_data = []
data_file = open("quiz_ques.txt", 'r')
cnt = 0
results = []
choices = []
for line in data_file.read().splitlines():
question_data = line.split(", ")
question_data.reverse() ; question = question_data.pop()
question_data.reverse() ; answer = question_data.pop()
q_options = question_data
question = Text(app, text=question)
question.text_color = 'white'
results.append(Text(app))
choices.append(ButtonGroup(app, options=q_options, command=check_answer, args=[answer, results[cnt], cnt]))
cnt = 1
score_txt = Text(app, color='white', size=40)
data_file.close()
app.display()