接收用户反馈后更新类内函数变量的问题求助
问题原因
程序启动时就创建了Question实例并调用了generate_question方法,此时用户还没选择运算,option是空字符串,触发了随机运算逻辑。点击Start按钮只是切换到问题界面,没有重新根据用户所选运算生成新问题,导致首次显示的还是启动时生成的随机问题。
修复方案
- 移除
Question类__init__方法里的self.generate_question()调用,避免启动时自动生成问题。 - 修改Start按钮的命令,切换界面后调用
app.generate_question(),用用户选择的运算生成对应问题。 - 可选:给单选按钮设置默认选中项,避免用户未选择就点击Start时仍使用随机运算。
修改后的完整代码
import tkinter as ttk1 from tkinter import * from tkinter import ttk import random root = Tk() def change_frame(frame): frame.tkraise() f1 = Frame(root) f2 = Frame(root) f1.grid(row=0, column=0, sticky='NSEW') f2.grid(row=0, column=0, sticky='NSEW') option = "" def select_question(value): global option option = value second_frame1 = ttk.LabelFrame(f1, text="How to Play") second_frame1.grid(row=1, column=0, padx=20, pady=10, sticky="NSEW") third_frame1 = ttk.LabelFrame(f1, text="Difficulty") third_frame1.grid(row=3, column=0, padx=20, pady=10, sticky="NSEW") radio1 = ttk.Radiobutton(third_frame1, text="plus", value="Addition", command=lambda:select_question("+")) radio1.grid(row=2, column=0, padx=18) radio1.invoke() # 设置默认选中加法,可选 radio2 = ttk.Radiobutton(third_frame1, text="minus", value="Subtraction", command=lambda:select_question("-")) radio2.grid(row=2, column=1, padx=18) radio3 = ttk.Radiobutton(third_frame1, text="times", value="Multiplication", command=lambda:select_question("*")) radio3.grid(row=2, column=2, padx=18) fourth_frame1 = ttk.LabelFrame(f1, text="Challenge") fourth_frame1.grid(row=4, column=0, padx=20, pady=10, sticky="NSEW") # 修改Start按钮命令,切换界面后生成对应问题 button = ttk.Button(fourth_frame1, text="Start", command=lambda: [change_frame(f2), app.generate_question()]) button.grid(row=3, column=2) top_frame2 = ttk.LabelFrame(f2, text="Question", height=100, width=200) top_frame2.grid(row=0, column=0, columnspan=10, rowspan=2, padx=20, pady=10, sticky="NSEW") class Question: def __init__(self, root1): self.root1 = root1 self.question_entry() # 移除初始化时的generate_question调用 def question_entry(self): self.question = ttk1.Label(top_frame2, text="") self.question.grid(pady=20) def generate_question(self): num1 = random.randint(1, 20) num2 = random.randint(1, 20) operation = option if operation == "": operators = ['+', '-', '*', '/'] operation = random.choice(operators) if operation == "+": self.correct_answer = num1 + num2 elif operation == "-": self.correct_answer = num1 - num2 elif operation == "*": self.correct_answer = num1 * num2 else: num1, num2 = num1 * num2, num1 self.correct_answer = num1 // num2 self.question.config(text=f"What is {num1} {operation} {num2}?") app = Question(root) change_frame(f1) root.mainloop()
关键修改点
- 移除
Question初始化时的generate_question调用,避免启动时生成随机问题。 - Start按钮的命令改为同时切换界面和调用
generate_question,确保用用户选择的运算生成问题。 - 可选添加
radio1.invoke()设置默认选中项,防止用户未选择就点击Start。
内容的提问来源于stack exchange,提问作者GruffCheetah628
相关产品推荐
相关产品推荐

