如何实现问答游戏的Entry题目切换、答错退出及题库文件读取?
Hey there! Let's tackle your three main game requirements one by one—switching to the next question when you get an answer right, exiting immediately on a wrong answer, and loading questions from a text file instead of hardcoding them. I'll walk you through each fix with modified code you can drop right into your project.
1. Auto-Switch Questions on Correct Answers + Exit on Wrong Ones
First, we need to add click handlers to your answer buttons so they can verify if the selected answer is correct. We'll also track your progress through the question list to move to the next question automatically when you get one right.
Key Tweaks:
- Organize all questions/options/answers into a list of dictionaries (this also makes it easier to load from a file later).
- Add a
current_question_idxvariable to keep track of which question you're on. - Write a
check_answerfunction that handles correct/wrong logic, updates the UI, or exits the game. - Bind this function to each answer button so clicking triggers the check.
2. Load Questions from a Text File
Instead of hardcoding every question, we'll use a simple text file format. Here's how to set it up:
Question File (questions.txt) Format:
Each line represents one question, split by pipes (|):
What's the capital of Nigeria|Mongoria|Cairo|Accra|Abuja|Abuja Which one of the colors can be found in the US National Flag|Green|Red|Orange|Yellow|Red What is 5000 x 110|55,110|56,100|50,000|55,000|55,000 Whitney Houston died in which year|2013|2010|2012|2011|2012 How many countries are there in Africa|32|43|45|30|45
(Fixed a typo "Yelow" to "Yellow" in the second question for accuracy)
Loading Function:
We'll add a load_questions function that reads this file and converts each line into a structured question entry.
Full Modified Code
Here's the complete code with all three requirements implemented:
from tkinter import * import tkinter as tk import pygame as py from PIL import ImageTk, Image import time, random, sys from pygame.locals import * py.init() py.mixer.init() root = Tk() root.title("Who Wants To Be A Millionaire") root.geometry('1352x625+0+0') # Fixed syntax error here (removed the equals sign) root.configure(background='black') abc = Frame(root, bg='black') abc.grid() abc1 = Frame(root, bg='black', bd=20, width=900, height=600) abc1.grid(row=0, column=0) abc2 = Frame(root, bg='black', bd=20, width=452, height=600) abc2.grid(row=0, column=1) abc1a = Frame(abc1, bg='black', bd=20, width=900, padx=110, height=200) abc1a.grid(row=0, column=0) abc1b = Frame(abc1, bg='black', bd=20, width=900, height=200) abc1b.grid(row=1, column=0) abc1c = Frame(abc1, bg='black', bd=20, width=900, height=200) abc1c.grid(row=2, column=0) # Track current question and store all questions current_question_idx = 0 questions = [] def load_questions(file_path): """Load questions from a text file into a structured list""" global questions with open(file_path, 'r', encoding='utf-8') as f: for line in f: line = line.strip() if not line: continue parts = line.split('|') if len(parts) != 6: print(f"Skipping invalid line: {line}") continue question_text, opt1, opt2, opt3, opt4, correct_ans = parts questions.append({ 'question': question_text, 'options': [opt1, opt2, opt3, opt4], 'correct': correct_ans }) def update_question(): """Update the UI with the current question and options""" if current_question_idx >= len(questions): textQues.delete(0, END) textQues.insert(0, "Congratulations! You won!") # Disable all buttons once the game ends text_option1.config(state=DISABLED) text_option2.config(state=DISABLED) text_option3.config(state=DISABLED) text_option4.config(state=DISABLED) return current_q = questions[current_question_idx] question1.set(current_q['question']) choice1.set(current_q['options'][0]) choice2.set(current_q['options'][1]) choice3.set(current_q['options'][2]) choice4.set(current_q['options'][3]) def check_answer(selected_ans): """Check if the answer is correct; move to next question or exit""" global current_question_idx current_q = questions[current_question_idx] if selected_ans == current_q['correct']: current_question_idx += 1 update_question() else: # Exit immediately on wrong answer root.destroy() sys.exit() # Load questions from the text file (ensure it's in the same folder as your script) load_questions('questions.txt') #===========================================UI Elements============================================== question1 = StringVar() choice1 = StringVar() choice2 = StringVar() choice3 = StringVar() choice4 = StringVar() textQues = Entry(abc1c, font=('arial',18, 'bold'), bg='black',fg='white', bd=2, width=50, justify=CENTER, textvariable=question1) textQues.grid(row=0, column=0, columnspan=10, pady=4) label_option1 = Label(abc1c, font=('arial',14, 'bold'), text='A: ', bg='black',fg='white', bd=5, justify=CENTER) label_option1.grid(row=2, column=0, pady=4, sticky=W) text_option1 = Button(abc1c, font=('arial',14, 'bold'), bg='blue',fg='white', bd=5, width=17, height=2, justify=CENTER, textvariable=choice1, command=lambda: check_answer(choice1.get())) text_option1.grid(row=2, column=1, pady=4) label_option2 = Label(abc1c, font=('arial',14, 'bold'), text='B: ', bg='black',fg='white', bd=5, justify=CENTER) label_option2.grid(row=2, column=2, pady=3, sticky=W) text_option2 = Button(abc1c, font=('arial',14, 'bold'), bg='blue',fg='white', bd=5, width=17, height=2, justify=CENTER, textvariable=choice2, command=lambda: check_answer(choice2.get())) text_option2.grid(row=2, column=3, pady=4) label_option3 = Label(abc1c, font=('arial',14, 'bold'), text='C:', bg='black',fg='white', bd=5, justify=CENTER) label_option3.grid(row=3, column=0, pady=4, sticky=W) text_option3 = Button(abc1c, font=('arial',14, 'bold'), bg='blue',fg='white', bd=5, width=17, height=2, justify=CENTER, textvariable=choice3, command=lambda: check_answer(choice3.get())) text_option3.grid(row=3, column=1, pady=4) label_option4 = Label(abc1c, font=('arial',14, 'bold'), text='D: ', bg='black',fg='white', bd=5, justify=CENTER) label_option4.grid(row=3, column=2, pady=4, sticky=W) text_option4 = Button(abc1c, font=('arial',14, 'bold'), bg='blue',fg='white', bd=5, width=17, height=2, justify=CENTER, textvariable=choice4, command=lambda: check_answer(choice4.get())) text_option4.grid(row=3, column=3, pady=4) raytxt = Label(abc2, font=('Cambri', 12, 'italic'), text='Built by: Raymond French ', bg='black', fg='white', bd=5, justify=CENTER) raytxt.grid(row=1, column=0) # Start with the first question update_question() root.mainloop()
Quick Notes:
- Make sure
questions.txtis saved in the same folder as your Python script, using the format shared above. - Fixed a small syntax error in your original code:
root.geometry=('1352x625+0+0')becameroot.geometry('1352x625+0+0')(removed the incorrect equals sign). - When you answer all questions correctly, the game shows a victory message and disables buttons.
- Clicking a wrong answer closes the window and exits the program immediately.
内容的提问来源于stack exchange,提问作者Lilian

