Replacing a window with a new one- Python tkinter



I’m creating a quiz game in Pythonn tkinter. I’m using my original window, called window in the beginning of the program. Then, if the user clicks on the START button, window gets replaced with window2 and the buttons that get created in the App class are displayed on window2. When I do that, it throws the following error:

Traceback (most recent call last):
  File "C:UsersMeiromPycharmProjectsquizmain.py", line 45, in <module>
    class App:
  File "C:UsersMeiromPycharmProjectsquizmain.py", line 47, in App
    def __init__(self, button1=MyButton(window2, 50, 200),
NameError: name 'window2' is not defined

My code:

from tkinter import *
from itertools import count


window = Tk()
window.title("Python Quiz")
width = window.winfo_screenwidth()
height = window.winfo_screenheight()
window.geometry("%dx%d" % (width, height))


def open_new_window():
    window2 = Toplevel(window)
    window2.title("Python Quiz")
    width2 = window2.winfo_screenwidth()
    height2 = window2.winfo_screenheight()
    window2.geometry("%dx%d" % (width2, height2))
    window.destroy()

open_new_window()


def start_command():
    destroy_list = [welcome, quit_button]

    for i in destroy_list:
        i.destroy()

    destroy_start()


def destroy_start():
    start_button.destroy()
    call = App()
    print(call.questions())
    open_new_window()


class MyButton(Button):
    def __init__(self, parent, x, y, **kwargs):
        super().__init__(parent, kwargs, activebackground="lightblue")
        self.place(x=x, y=y)


class App:
    counter = count(0)
    def __init__(self, button1=MyButton(window2, 50, 200),
                 button2 = MyButton(window2, 150, 200),
                 button3 = MyButton(window2, 250, 200),
                 button4 = MyButton(window2, 350, 200)):
        self.button1 = button1.configure(command=lambda: self.button1)
        self.button2 = button2.configure(command=lambda: self.button2)
        self.button3 = button3.configure(command=lambda: self.button3)
        self.button4 = button4.configure(command=lambda: self.button4)
        self.counter = next(self.counter)
        self.button1 = button1
        self.button2 = button2
        self.button3 = button3
        self.button4 = button4

        if self.counter > 5:
            return

    def questions(self):
        questions_list = ["What is the data type of the following object?: 3.5",
                          "What is a correct syntax to output "Hello World" in Python?",
                          "How do you insert COMMENTS in Python code?",
                          "Which one is NOT a legal variable name?",
                          "How do you create a variable with the NUMERIC value 5?",
                          "What is the output of the following code?",
                          "What is the output of the following code?",
                          "What is the output of the following code?",
                          "What is the output of the following code?"]

        answers = [["float", "int", "str", "bool"],
                   ["printf("Hello World")", "print(Hello World)", "print("Hello World")", "print"(Hello)""],
                   ["\ COMMENT", "// COMMENT", "/* COMMENT */", "# COMMENT"],
                   ["MyVar", "my-var", "_myVar", "my_var"],
                   ["x == 5", "x = int(5)", "x = 5", "Options 2 and 3 are both correct"],
                   [955, 3692, -1, 105],
                   ["The sum is 6", "The sum is 4", "The sum is 5", "The sum is 22"],
                   ["True", "yes", "False", "no"],
                   ["100 97 180 99 101", "100 180 101", "97 99", "None ofnthe above"]]

        correct_answers = [0, 2, 3, 1, 3, 1, 2, 3, 0]

        question_num.configure("Question #%d" % self.counter)
        question_num.place(x=230, y=20)
        questions_label.configure(questions_list[self.counter - 1])
        self.button1.configure(text=answers[self.count - 1][0])
        self.button2.configure(text=answers[self.count - 1][1])
        self.button3.configure(text=answers[self.count - 1][2])
        self.button4.configure(text=answers[self.count - 1][3])

        if self.counter > 5:
            question_read = open("question%d.txt" % self.counter, "r")
            code_label.configure(text=question_read.readlines())
            question_read.close()
            code_label.place(x=230, y=100)

        return correct_answers[self.counter - 1]


welcome = Label(window, text="Welcome the Python Quiz!", font=("Arial Rounded MT Bold", 50))
welcome.place(x=230, y=20)

start_button = Button(window, text="START", bg="lime", font=("Arial Rounded MT Bold", 50), width=7,
                              command=start_command)
start_button.place(x=470, y=220)

quit_button = Button(window, text="QUIT", bg="red", font=("Arial Rounded MT Bold", 50), width=7,
                             command=lambda: quit())
quit_button.place(x=470, y=370)
question_label = Label(window, font=("Arial Rounded MT Bold", 30))
question_num = Label(window)
code_label = Label(window)


mainloop()

The content of the text files used in the program:

question6.txt:

def max_num(num1, num2, num3):
  if num1 >= num2 and num1 >= num3:
    print(num1)
  elif num2 >= num1 and num2 >= num3:
    print(num2)
  else:
    print(num3)

max_num(3692,955,105)

question7.txt:

def count_digit (num):
    sum= 0
    while num>=1:
         sum=sum+num%10
         num=num//10
    print("The sum is: " + str(sum))

count_digit(63625)

question8.txt:

def is_there_char(str):
    if str.find("!") == -1:
        print("no")
    else:
        print("yes")

is_there_char("pink")

question9.txt:

my_dict = {
  "32233344": 100,
  "08098509": 97,
  "22222299": 180,
  "23563346" : 99,
  "22224444" : 101
}
for key in my_dict:
    if my_dict [key] >90:
        print(my_dict[key])

How can I solve the problem?

Answer

In your class app you reference window2 def __init__(self, button1=MyButton(window2, 50, 200), but it is not defined globally it only exists within open_new_window().



Source: stackoverflow