Tkinter测验应用messagebox分数始终为0的问题排查求助
Tkinter测验应用分数始终为0的问题修复
错误原因
- score变量未实时更新:原代码中
score = len(user_ans)*10在play函数初始化时就执行,此时user_ans是空列表,score被固定为0,后续用户答对题目更新user_ans后,score不会自动重新计算。 - 题目索引匹配逻辑不可靠:通过
qsn["text"] == ques[i]查找当前题目索引,效率低且易出错——比如初始化时qsn文本为空,会导致匹配失败,无法正确判断答案。 - 随机出题存在重复:使用
random.randint(0,2)会导致题目重复出现,无法保证3道题各展示一次。
修复后的代码
import tkinter as tk from tkinter import messagebox import random def play(): wind2 = tk.Toplevel() v = tk.IntVar() ques = ["Identify the least stable ion amongst the following.", "The set representing the correct order of first ionisation potential is", "The correct order of radii is"] o1 = ["", "Li⁺", "Be⁻", "B⁻", "C⁻"] o2 = ["", "K > Na > Li", "Be > Mg >Ca", "B >C > N", "Ge > Si >C"] o3 = ["", "N < Be < B", "F⁻ < O²⁻ < N³⁻", "Na < Li < K", "Fe³⁺ < Fe⁴⁺ < Fe²⁺"] choice = [o1, o2, o3] ans = [2, 2, 2] user_ans = [] current_q_idx = 0 # 生成随机不重复的题目顺序 q_order = random.sample(range(len(ques)), len(ques)) def selection(): selected = v.get() # 直接用当前题目索引判断答案 if ans[q_order[current_q_idx]] == selected: print("Correct Answer") user_ans.append((q_order[current_q_idx], selected)) def nxt(): nonlocal current_q_idx # 第一次点击Go时销毁输入组件 if nxt.count == 0: name.destroy() nmbox.destroy() nmbut.destroy() # 判断是否完成所有题目 if current_q_idx >= len(q_order): # 实时计算分数 score = len(user_ans)*10 messagebox.showinfo("score", str(score)) wind2.destroy() return # 更新当前题目内容 q_idx = q_order[current_q_idx] qsn['text'] = ques[q_idx] qsn.pack() r1['text'] = choice[q_idx][1] r2['text'] = choice[q_idx][2] r3['text'] = choice[q_idx][3] r4['text'] = choice[q_idx][4] r1.pack() r2.pack() r3.pack() r4.pack() nbut.pack() current_q_idx += 1 nxt.count += 1 nxt.count = 0 name = tk.Label(wind2, text = "Enter your name below:") nmbox = tk.Entry(wind2, bd = 4) nmbut = tk.Button(wind2, text = "Go", command = nxt) name.pack() nmbox.pack() nmbut.pack() qsn = tk.Label(wind2) r1 = tk.Radiobutton(wind2, variable = v, value = 1, command=selection) r2 = tk.Radiobutton(wind2, variable = v, value = 2, command=selection) r3 = tk.Radiobutton(wind2, variable = v, value = 3, command=selection) r4 = tk.Radiobutton(wind2, variable = v, value = 4, command=selection) nbut = tk.Button(wind2, text = "next", command = nxt)
关键修改点
- 实时计算分数:在弹出分数时直接计算
len(user_ans)*10,避免score变量提前固定为0。 - 记录当前题目索引:新增
current_q_idx和q_order(随机不重复的题目顺序),直接通过索引匹配题目和答案,避免文本匹配的错误。 - 修复出题逻辑:使用
random.sample生成不重复的题目顺序,确保所有题目各展示一次。 - 优化nxt函数逻辑:区分第一次点击Go和后续点击next的操作,完成所有题目后弹出分数并关闭窗口。
内容的提问来源于stack exchange,提问作者ayushkumarbiswal
相关产品推荐
相关产品推荐

