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

如何在Python问答应用中实现点击按钮后循环加载新问题?

解决GooeyPie中文问答应用无法加载下一题的问题

问题出在你用了命令行式的while循环思路,GooeyPie是事件驱动的GUI框架,按钮点击的回调函数是独立执行的,continue根本没法触发主循环刷新界面。要实现点击后加载新问题,得按GUI的逻辑来:

核心修改思路

  1. 把「加载新问题」的逻辑封装成独立函数,负责生成随机单词、选项,更新界面上的标签和按钮文本。
  2. 在按钮的点击回调里,先处理用户的选择(判断对错),然后直接调用这个加载函数刷新界面。
  3. 程序初始化时先调用一次加载函数,显示第一个问题。

代码示例(基于常见结构修改)

假设你的原有代码结构类似,修改后如下:

from gooeypie import GooeyPieApp, Label, Button, RadioGroup
import random

# 模拟单词库
word_list = [
    {"word": "苹果", "correct": "apple", "wrong": "banana"},
    {"word": "香蕉", "correct": "banana", "wrong": "orange"},
    {"word": "橘子", "correct": "orange", "wrong": "grape"},
    # 可添加更多单词
]

class QuizApp(GooeyPieApp):
    def __init__(self):
        super().__init__("中文单词问答")
        # 创建界面元素
        self.word_label = Label(self, "")
        self.option_group = RadioGroup(self, ["", ""])
        self.submit_btn = Button(self, "提交", self.on_submit)
        
        # 布局设置
        self.add(self.word_label, 0, 0, column_span=2, padding=10)
        self.add(self.option_group, 1, 0, column_span=2, padding=10)
        self.add(self.submit_btn, 2, 0, column_span=2, padding=10)
        
        # 初始化加载第一个问题
        self.load_new_question()
    
    def load_new_question(self):
        # 随机选取单词
        current_word = random.choice(word_list)
        # 更新单词展示标签
        self.word_label.text = f"请选择「{current_word['word']}」的正确英文:"
        # 随机打乱选项顺序
        options = [current_word['correct'], current_word['wrong']]
        random.shuffle(options)
        # 更新单选框选项
        self.option_group.set_options(options)
        # 保存正确答案,供后续判断使用
        self.correct_answer = current_word['correct']
    
    def on_submit(self, event):
        # 获取用户选择
        user_choice = self.option_group.selected
        # 判断对错(可替换为弹窗/标签提示)
        if user_choice == self.correct_answer:
            print("答对了!")
        else:
            print(f"答错了,正确答案是:{self.correct_answer}")
        # 加载下一个问题
        self.load_new_question()

if __name__ == "__main__":
    app = QuizApp()
    app.run()

关键说明

  • 去掉原来的while循环,GooeyPie的app.run()本身就是主事件循环,负责处理所有用户交互。
  • 每次点击按钮后,通过load_new_question()直接更新界面元素的内容,GUI会自动完成刷新。
  • 用实例变量self.correct_answer存储当前问题的正确答案,方便回调函数判断用户选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 09:35:22