单选刷题程序

前段时间期末,有一个考试。老师以前出了一个题库,让我想起来小时候用学(游)习(戏)机刷题玩,刷几遍就都背下来了,于是写了这么一个东西

import tkinter as tk
import random
import os


class QuizApp:
    def __init__(self, questions, answers, mode):
        self.option_vars = ['A', 'B', 'C', 'D']
        self.questions = questions
        self.answers = answers
        self.mode = mode
        self.total_questions = len(self.questions)
        self.correct_count = 0
        self.total_attempts = 0
        self.current_question_index = 0
        self.correct_answer = ''

        self.root = tk.Tk()
        self.root.title("选择题答题程序")

        # 设置窗口大小
        self.root.geometry("600x400")

        # 设置字体
        self.font = ("SimSun", 16)
        self.question_font = ("SimSun", 18, "bold")

        self.question_label = tk.Label(self.root, text="", wraplength=580, justify="left", padx=20, pady=20, font=self.question_font)
        self.question_label.pack()

        self.option_buttons = []
        options = ['A', 'B', 'C', 'D']
        for option in options:
            button = tk.Button(self.root, text=option, width=15, height=2, command=lambda o=option: self.submit_answer(o), font=self.font)
            button.pack(pady=10)
            self.option_buttons.append(button)

        self.status_label = tk.Label(self.root, text="当前正确率: 0/0 (0.00%)", font=self.font)
        self.status_label.pack(pady=20)

        if self.mode == 'random':
            combined = list(zip(self.questions, self.answers))
            random.shuffle(combined)
            self.questions, self.answers = zip(*combined)

        self.display_next_question()

    def display_next_question(self):
        if self.current_question_index < self.total_questions:
            question_lines = self.questions[self.current_question_index].split('\n')
            question_text = question_lines[0]
            options = question_lines[1:5]

            # 找到当前正确答案
            correct_answer = self.answers[self.current_question_index]

            # 找到当前正确答案在选项中的位置
            current_correct_index = next(i for i, option in enumerate(options) if option.startswith(correct_answer))

            # 更新正确答案为随机选择的答案
            self.correct_answer = self.option_vars[current_correct_index]

            # 更新题目文本,包括问题和选项
            updated_question = '\n'.join([question_text] + options)

            self.question_label.config(text=updated_question)
            # 启用按钮
            for button in self.option_buttons:
                button.config(state=tk.NORMAL)
        else:
            self.current_question_index = 0
            if self.mode == 'random':
                combined = list(zip(self.questions, self.answers))
                random.shuffle(combined)
                self.questions, self.answers = zip(*combined)
            self.display_next_question()

    def submit_answer(self, selected_option):
        judge = False

        if selected_option == self.correct_answer:
            self.correct_count += 1
            answer_status = "恭喜,答案正确!"
        else:
            answer_status = f"答案错误。正确答案是 {self.correct_answer}。"
            judge = True

        self.total_attempts += 1
        accuracy = self.correct_count / self.total_attempts * 100 if self.total_attempts > 0 else 0
        self.status_label.config(text=f"{answer_status} 当前正确率: {self.correct_count}/{self.total_attempts} ({accuracy:.2f}%)")

        # 禁用按钮,避免重复提交
        for button in self.option_buttons:
            button.config(state=tk.DISABLED)

        self.current_question_index += 1
        if judge:
            self.root.after(2000, self.display_next_question)  # 等待2秒后显示下一题
        else:
            self.display_next_question()

    def run(self):
        self.root.mainloop()


def load_questions_and_answers(questions_file, answers_file):
    with open(questions_file, 'r', encoding='utf-8') as qf, open(answers_file, 'r', encoding='utf-8') as af:
        questions = qf.read().strip().split('\n\n')
        answers = af.read().strip().split('\n')
    return questions, answers


def main():
    questions_file = 'questions.txt'
    answers_file = 'answers.txt'

    if not (os.path.exists(questions_file) and os.path.exists(answers_file)):
        print("选择题文件或答案文件不存在!")
        return

    questions, answers = load_questions_and_answers(questions_file, answers_file)

    mode = input("请选择模式 (1: 顺序, 2: 随机): ").strip()
    if mode not in ['1', '2']:
        print("无效的模式选择!")
        return

    app = QuizApp(questions, answers, mode='sequential' if mode == '1' else 'random')
    app.run()


if __name__ == "__main__":
    main()

程序会读取同文件夹下的两个文件,格式大概是这样:

反正就这样,问题算上空行六行一个(题目,四个选项,一个空行),答案一行一个,不空行。

我是搞了个正则程序的,但不是很靠谱,就不发了。

效果如下

两个模式,顺序就顺序出题,乱序就随机出题

答对直接过,答错就停两秒,看看正确答案

祝各位期末能用上,然后选择题都对。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值