2

How can I use an entry.get which is in a function again in another function ?

I want to use answer1.get which is in def question1() again in question2()...

So I want this:

if the users give the right answer to the 1st question then they can see the 2nd one, else they should give the right answer to the 1st question

is that possible ?

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()
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
Ozzz
  • 29
  • 5

2 Answers2

0

You can't use a function declared inside of one function in another. Just move check() outside of question1() declaration.

As a side note, you rarely want to declare nested functions anyway as you want to keep your functions reasonably short.

Amongalen
  • 3,101
  • 14
  • 20
0

Firstly, move the check() function out of question1(). This is for the same reason as mentioned by @Amongalen.

Then you can put this code in the check() function:

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)
InfoDaneMent
  • 326
  • 3
  • 18
  • well thank you for your answers...however when I tried this I got an error.. line 22, in check if "shopping" in answer1.get(): NameError: name 'answer1' is not defined – – Ozzz Dec 04 '21 at 06:27
  • @Ozzz I am very late (2 years late) and you have probably already solved this or abandoned this project (I hope it is the former :) ) but I think you can use `globals()["answer1"]` – InfoDaneMent Apr 08 '23 at 06:01