Mar-03-2021, 02:10 PM
My head was stuck in the world of paper tests. The code is shorter, and the test better if you combine the choices with the answer. This code puts all the choices in the option menu.
import random import tkinter as tk answers = [] HISTORY = [ { 'Q': "In which year did World War II end?", 'A': ("1945", "1942", "1980", "2021")}, { 'Q': "What was used to encript German and Japanese messages?", 'A': ("Enigma", "Axis", "Enola", "Blitz", )}, { 'Q': "Which countries fought on the Eastern Front of World War II?", 'A': ("Germany/Soviet Union", "Britain/Germany", "Switzerland/Italy", "United States/Japan")}, { 'Q': "What was the code name for the allied invasion of Normandy?", 'A': ("D-Day", "VJ Day", "VE Day", "French Resistance")}, { 'Q': "In 1945 which two Japanese cities were nuclear bombs detonated?", 'A': ("Hiroshima/Nagasaki", "Tokyo/Hiroshima", "Tokyo/Nagasaki"), }] def quiz(window, title, questions, bg='white', fg='black'): window.title(title) window.configure(bg=bg) tk.Label(window, text=title, bg=bg, fg=fg).pack() for question in questions: tk.Label(window, text='', bg=bg, fg=fg).pack() tk.Label(window, text=question['Q'], bg=bg, fg=fg).pack() answer = tk.StringVar() choices = random.sample(question['A'], len(question['A'])) option = tk.OptionMenu(window, answer, *choices) option.configure(fg=fg, bg=bg) option.pack() answers.append((answer, question)) def score_quiz(questions): score = 0 for answer, question in questions: if answer.get() == question['A'][0]: score += 1 else: print(f'{question["A"][0]} is the answer to {question["Q"]}') print('Score =', score) root = tk.Tk() quiz(root, 'History', HISTORY) tk.Button(root, text='Check Answers', command=lambda: score_quiz(answers)).pack(pady=10) root.mainloop()My thinking about how to store the test questions was also stuck in the past. Instead of having a separate field for the answer, why not order the questions such that the first answer is always the correct answer. It makes it easier to write the questions. Of course we don't want a multiple choice test to use "A" as the correct answer for every question, so the choices get shuffled each time the test is taken.