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

Tkinter如何跨函数调用Entry组件的get方法实现答题权限控制

该需求完全可以实现。你当前代码无法运行的核心原因是 answer1 是 question1() 函数内的局部变量,函数作用域隔离导致外部的 question2() 无法直接访问这个对象,调用未定义的 answer.get() 会直接抛出异常。

最小改动解决方案(基于现有代码逻辑)

我们可以通过全局变量存储第一题的输入框对象、答题状态,即可快速实现你要的效果,修改后完整代码如下:

from tkinter import *

screen = Tk()

screen.geometry("1540x821")
screen.title("Exam")
screen.state("zoomed")
screen.resizable(0, 0)

# 新增全局变量:存储第一题输入框、第一题是否答对状态
is_q1_correct = False
answer1 = None

def question1():
    global answer1
    q1 = Label(screen, text="This is the Question 1 : ")
    q1.pack()

    a1 = StringVar()
    answer1 = Entry(screen, textvariable=a1)
    answer1.pack()

    def check():
        global is_q1_correct
        # 每次校验先清空之前的提示文字,避免重复叠加
        for widget in screen.place_slaves():
            if isinstance(widget, Label) and widget.winfo_y() == int(0.1*screen.winfo_height()):
                widget.destroy()

        if "shopping" in answer1.get():
            correct = Label(screen, text="correct answer")
            correct.place(relx=0.5, rely=0.1)
            is_q1_correct = True
        else:
            wrong = Label(screen, text="wrong answer")
            wrong.place(relx=0.5, rely=0.1)
            is_q1_correct = False

    buttoncheck = Button(screen, text="Check", command=check)
    buttoncheck.place(relx=0.5, rely=0.4)


def question2():
    # 先校验第一题状态,再判断是否展示第二题
    if is_q1_correct and answer1 is not None and "shopping" in answer1.get():
        q2 = Label(screen, text="This is the Question 2 : ")
        q2.pack()

        a2 = StringVar()
        answer2 = Entry(screen, textvariable=a2)
        answer2.pack()
    else:
        # 清空之前的第二题组件避免叠加
        for widget in screen.pack_slaves():
            if isinstance(widget, (Label, Entry)) and "Question 2" in str(widget.cget("text")):
                widget.destroy()
        previous = Label(screen, text="go back to previous question")
        previous.pack()


button1 = Button(screen, text="Start", command=question1)
button1.place(relx=0.5, rely=0.5)

button2 = Button(screen, text="Next", command=question2)
button2.place(relx=0.5, rely=0.6)

screen.mainloop()

补充优化建议

如果后续需要扩展更多题目,建议用类封装所有答题相关的属性和方法,避免全局变量过多导致后续维护混乱,代码结构会更清晰。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:15:04