You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Tkinter按钮调用函数的返回值以实现答题校验?

解决Tkinter测验程序的答题校验问题

修改思路

核心是把当前题目编号设为闭包内可共享的变量,在切换题目时先完成上一题的答案校验,再更新题目内容。具体改动如下:

  • 在play()函数内定义current_q变量,记录当前显示的题目索引(初始为0,对应第一题)
  • 移除冗余的selection()函数,直接通过v.get()获取用户选中的选项值
  • 修改nxt()函数,先校验当前题目的答案,再切换到新题目并更新current_q
  • 添加结果提示标签,实时反馈答题对错

修改后的完整代码

import tkinter as tk
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]
    
    # 初始化当前题目索引
    current_q = 0
    
    qsn = tk.Label(wind2, text=ques[current_q])
    qsn.pack()
    
    # 添加结果提示标签
    result_label = tk.Label(wind2, text="", fg="red")
    result_label.pack()
    
    r1 = tk.Radiobutton(wind2, text=o1[1], variable=v, value=1)
    r2 = tk.Radiobutton(wind2, text=o1[2], variable=v, value=2)
    r3 = tk.Radiobutton(wind2, text=o1[3], variable=v, value=3)
    r4 = tk.Radiobutton(wind2, text=o1[4], variable=v, value=4)
    r1.pack()
    r2.pack()
    r3.pack()
    r4.pack()

    def nxt():
        nonlocal current_q
        # 校验当前题目的答案
        selected = v.get()
        if selected == ans[current_q]:
            result_label.config(text="回答正确!", fg="green")
        else:
            result_label.config(text=f"回答错误,正确答案是选项{ans[current_q]}", fg="red")
        
        # 切换到新题目
        new_q = random.randint(0, 2)  # 修正范围:覆盖所有3道题目
        current_q = new_q
        qsn['text'] = ques[current_q]
        r1['text'] = choice[current_q][1]
        r2['text'] = choice[current_q][2]
        r3['text'] = choice[current_q][3]
        r4['text'] = choice[current_q][4]
        # 重置单选框选中状态
        v.set(0)
    
    nbut = tk.Button(wind2, text="next", command=nxt)
    nbut.pack()

# 测试运行
root = tk.Tk()
tk.Button(root, text="开始测验", command=play).pack()
root.mainloop()

关键改动说明

  • 使用nonlocal current_q让内部函数nxt()可以修改外部play()函数里的current_q变量
  • 每次点击next按钮时,先获取用户当前选中的选项,和对应题目的正确答案比对,通过标签显示反馈
  • 修正随机题目范围为0-2,确保所有题目都能被选中
  • 切换题目后重置单选框选中状态,避免残留上一题的选择

内容的提问来源于stack exchange,提问作者ayushkumarbiswal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 05:25:53