【问题标题】:How to use an Entry widget in a fuction from another function如何在另一个函数的函数中使用 Entry 小部件
【发布时间】:2022-01-07 21:01:58
【问题描述】:

如何在另一个函数中再次使用一个函数中的 entry.get ?

我想在def question1() 中再次使用answer1.get question2()...

所以我想要这个:

如果用户对第一个问题给出了正确的答案,那么他们可以看到第二个问题,否则他们应该对第一个问题给出正确的答案

这可能吗?

from tkinter import *

screen = Tk()

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


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

    a1 = StringVar()

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

    def check():

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

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


def question2():
    if "shopping" in answer.get():

        q2 = Label(screen, text="This is the Question 2 : ")
        q2.pack()

        a2 = StringVar()

        answer2 = Entry(screen, textvariable=a2)
        answer2.pack()

    else:
        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()

【问题讨论】:

    标签: python user-interface tkinter tkinter-entry


    【解决方案1】:

    首先,将check() 函数移出question1()。这与@Amongalen 提到的原因相同。

    然后你可以把这段代码放在check()函数中:

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

    【讨论】:

    • 非常感谢您的回答...但是当我尝试此操作时出现错误...第 22 行,检查 answer1.get() 中是否“购物”:NameError: name 'answer1'未定义——
    【解决方案2】:

    您不能在另一个函数中使用在一个函数内部声明的函数。只需将check() 移出question1() 声明即可。

    附带说明一下,您很少希望声明嵌套函数,因为您希望函数保持合理的简短。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-30
      • 1970-01-01
      • 2020-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多