Home > Enterprise >  Create Functions for New Windows in Python
Create Functions for New Windows in Python

Time:10-22

I have a function that creates a new window and updates some values to insert into one of the Entry widgets in the new window, as part of a times table quiz. I then need to create a new function that runs when the submit button is clicked and checks that the user's answer is correct. However, this new function gives me a NameError when it runs because it cannot identify that widgets in the new window, only checking the widgets in the original window. How do I get it to check the widgets in the new window? Original window:

Label(window,text="TIMES TABLES").pack()
game_btn = Button(window, text="Play Game",command=playGameClicked)
game_btn.pack()

Function that creates new window:

def playGameClicked():
    #create new window
    newWindow = Toplevel(window)
    newWindow.geometry("500x300 0 0")
    Label(newWindow, text = "Times Tables Game").pack()    
    Label(newWindow,text="Question:",font=("Helvetica",10),width=10,).pack()
    question_box = Entry(newWindow,width=30,background="light blue")
    question_box.pack()
    Label(newWindow,text="Your Answer:",font=("Helvetica",10),width=10).pack()
    answer_box = Entry(newWindow,width=50,background="light green")
    answer_box.pack()
    submit_btn = Button(newWindow,text="Submit",width=10,command=submitClicked)
    submit_btn.pack()
    Label(newWindow,text="You are...",font=("Helvetica",10),width=10).pack()
    correction_box = Text(newWindow,width=15,height=1,background="light blue")
    correction_box.pack()

    #new question (all_tables_dict is a long dictionary of 1-12xtables e.g"1*2":2)
    question_box.delete(0,END)
    keys = list(all_tables_dict.keys())
    new_question = random.choice(keys)
    question_box.insert(END, new_question)

When the submit button is clicked: (this is the function that doesn't work)

def submitClicked():
    answer_box.get(0.0,END)
    try:
        answer = all_tables_dict[question]
        correct=True
    except:
        correct=False
    if correct==True:
        correction_box.insert("CORRECT!")
    else:
        correction_box.insert("INCORRECT!")

CodePudding user response:

You didn't show full error message and I can't run it so I will guess

All variables created inside function are local and they can't be accessed in other functions. You have to inform function that it has to assign widget to global variable.

def playGameClicked():
    global answer_box
    global correction_box

    # ... code ...

    answer_box = ...

    # ... code ...

    correction_box = ...

    # ... code ...
  • Related