Bibek Bhandari
Bibek Bhandari

Reputation: 3

How to make the label appear on the window?

I have the following code and I want the label ("Correct answer to appear on the window.") I am getting 'window is not defined error'. How do I resolve it.

    class Game:
        def __init__(self, window):

            self.label = Label(window, text="Welcome to the game", font=("arial 35 bold"))
            self.label.place(x=0, y=0)

            # question goes here
            self.qn1 = Label(window, text=q, font=('arial 20 bold'))
            self.qn1.place(x=50, y=70)

            # entry
            self.ans = StringVar()
            self.qnent1 = Entry(window, width=25, textvariable=self.ans)
            self.qnent1.place(x=150, y=120)

            self.btn1 = Button(window, text="Next", width=20, height=2, bg='steelblue', command=self.check)
            self.btn1.place(x=150, y=150)


        def check(self):
            game = (self.qnent1.get())
            if game.lower() == ans:
                print("Correct answer")
                label = Label(window, text="Correct Answer", font=('arial 20 bold'), fg='green')
                label.pack()

            else:
                print(self.ans.get())
                print("Wrong answer")


    start = Tk()
    c = Game(start)
    start.geometry("640x320+0+0")
    start.mainloop()

Upvotes: 0

Views: 47

Answers (1)

Keyur Potdar
Keyur Potdar

Reputation: 7238

Add self.window = window after the def __init__(self, window): line and replace all window's inside both functions with self.window

It should solve your problem.

Your code with corrections:

class Game:
    def __init__(self, window):
        self.window = window

        self.label = Label(self.window, text="Welcome to the game", font="arial 35 bold")
        self.label.place(x=0, y=0)

        # question goes here
        self.qn1 = Label(self.window, text=q, font='arial 20 bold')
        self.qn1.place(x=50, y=70)

        # entry
        self.ans = StringVar()
        self.qnent1 = Entry(self.window, width=25, textvariable=self.ans)
        self.qnent1.place(x=150, y=120)

        self.btn1 = Button(self.window, text="Next", width=20, height=2, bg='steelblue', command=self.check)
        self.btn1.place(x=150, y=150)

    def check(self):
        game = (self.qnent1.get())
        if game.lower() == ans:
            print("Correct answer")
            label = Label(self.window, text="Correct Answer", font='arial 20 bold', fg='green')
            label.pack()

        else:
            print(self.ans.get())
            print("Wrong answer")


start = Tk()
c = Game(start)
start.geometry("640x320+0+0")
start.mainloop()

Upvotes: 1

Related Questions