Tkinter多选测验应用无法切换题目及抽题、Excel导出功能实现问题
Tkinter多选题测验应用问题修复方案
问题定位
- 问题1(题目无法切换):
display_question方法每次调用都会新建一个Label控件,旧的题目Label没有被销毁或更新,新控件堆叠在旧控件下方,视觉上看起来始终停留在第一题。此外你代码中调用的display_title方法没有对应实现,也会引发报错。 - 问题2(随机抽题逻辑缺失):当前代码直接固定使用全部easy题库,没有实现按比例随机抽取easy、hard题库题目的逻辑。
- 问题3(作答记录保存不符合要求):当前
submit方法只保存了总对错数,没有存储抽题编号、单题作答记录,也没有按照你要求的格式写入Excel。
完整修改代码
import tkinter as tk import tkinter.ttk as ttk import random from openpyxl import Workbook from tkinter import messagebox as mb # 题库定义(如果是从questionslist导入可以替换下面的题库代码) easy_questions2=[ "1e. Name?", "2e. Last name?", "3e. Birthdate?", "4e. Food?" ] easy_options=[ ['Marck', 'Mary','Joseph','John'], ['Smith', 'Hartnett','Pitt','Pacino'], ['June', 'October','November','April'], ['All', 'Fries','Pasta','Chicken'] ] easy_answers=[ 1, 2, 3, 3 ] hard_questions2=[ "1h. Number?", "2h. Word?", "3h. Hour?", "4h. Color?" ] hard_options=[ ['10', '11','21','55'], ['Book', 'Table','en','Pacino'], ['11', '21','24','18'], ['Yellow', 'Blue','Red','Green'] ] hard_answers=[ 3, 4, 1, 2 ] class MainApplication(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.q_no=0 self.correct=0 # 存储用户作答记录和抽题编号 self.user_answers = [] self.selected_q_ids = [] # 随机抽题逻辑:示例题库题量少暂时各抽2道,实际题量足够后改成各抽5道即可 selected_easy_idx = random.sample(range(len(easy_questions2)), 2) selected_hard_idx = random.sample(range(len(hard_questions2)), 2) # 合并抽中的题目、选项、答案、编号 self.question = [] self.options = [] self.answer = [] for idx in selected_easy_idx: self.question.append(easy_questions2[idx]) self.options.append(easy_options[idx]) self.answer.append(easy_answers[idx]) self.selected_q_ids.append(easy_questions2[idx].split('.')[0]) for idx in selected_hard_idx: self.question.append(hard_questions2[idx]) self.options.append(hard_options[idx]) self.answer.append(hard_answers[idx]) self.selected_q_ids.append(hard_questions2[idx].split('.')[0]) self.data_size = len(self.question) self.display_title() # 题目Label改为类属性,避免重复新建 self.q_label = tk.Label(self, width=60) self.q_label.pack(padx=19, pady=31, anchor="w") self.display_question() self.opt_selected=tk.IntVar() self.opts=self.radio_buttons() self.display_options() self.buttons() def display_title(self): title = tk.Label(self, text="多选题测验", font=("微软雅黑", 16, "bold")) title.pack(pady=10) def display_result(self): wrong_count = self.data_size - self.correct correct = f"Correct: {self.correct}" wrong = f"Wrong: {wrong_count}" score = int(self.correct / self.data_size * 100) result = f"Score: {score}%" mb.showinfo("Result", f"{result}\n{correct}\n{wrong}") def check_ans(self, q_no): if self.opt_selected.get() == self.answer[q_no]: return True def next_button(self): # 记录当前作答 current_ans = self.opt_selected.get() self.user_answers.append(current_ans) if self.check_ans(self.q_no): self.correct += 1 self.q_no += 1 if self.q_no==self.data_size: self.display_result() self.submit() self.destroy() else: self.display_question() self.display_options() def buttons(self): next_button = tk.Button(self, text="Next",command=self.next_button, width=10) next_button.pack(pady=50, side="bottom") def display_options(self): val=0 self.opt_selected.set(0) for option in self.options[self.q_no]: self.opts[val]['text']=option val+=1 def display_question(self): # 直接更新题目Label的文本,不新建控件 self.q_label.config(text=self.question[self.q_no]) def radio_buttons(self): q_list = [] while len(q_list) < 4: radio_button = ttk.Radiobutton(self,text=" ",variable=self.opt_selected, value = len(q_list)+1) q_list.append(radio_button) radio_button.pack(padx=19, anchor="w") return q_list def submit(self): # 新建Excel文件,无需模板 wb = Workbook() sheet = wb.active # 按要求格式写入 # 第一行:题号1~10 sheet.cell(row=1, column=1).value = "" for col in range(self.data_size): sheet.cell(row=1, column=col+2).value = col+1 # 第二行:抽题编号 sheet.cell(row=2, column=1).value = "question" for col, q_id in enumerate(self.selected_q_ids): sheet.cell(row=2, column=col+2).value = q_id # 第三行:用户作答 sheet.cell(row=3, column=1).value = "answer" for col, ans in enumerate(self.user_answers): sheet.cell(row=3, column=col+2).value = ans # 可选:追加总得分信息 sheet.cell(row=5, column=1).value = "总正确数" sheet.cell(row=5, column=2).value = self.correct sheet.cell(row=6, column=1).value = "总错误数" sheet.cell(row=6, column=2).value = self.data_size - self.correct excel_filename = "D:\\Python\\quiz\\data.xlsx" wb.save(excel_filename) if __name__ == "__main__": root = tk.Tk() MainApplication(root).pack(side="top", fill="both", expand=True) root.title("Quiz") root.geometry('800x450') root.mainloop()
使用说明
- 需提前安装依赖:执行
pip install openpyxl - 当前示例题库easy、hard各只有4道题,代码里抽题数暂时设为各2道,等你实际题库满足题量后,将
random.sample(range(len(easy_questions2)), 2)改成random.sample(range(len(easy_questions2)),5),hard同理即可 - 生成的Excel文件会保存在
D:\Python\quiz\data.xlsx,格式完全符合你要求的结构
内容的提问来源于stack exchange,提问作者Kome Gognome
相关产品推荐
相关产品推荐

