如何让标签出现在窗口上?

时间:2018-01-04 08:06:25

标签: python user-interface tkinter

我有以下代码,我想要标签("正确的答案出现在窗口上。")我得到的窗口未定义错误'。我该如何解决呢。

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

1 个答案:

答案 0 :(得分:1)

self.window = window行之后添加def __init__(self, window):,并使用window

替换这两个函数中的所有self.window

它应该可以解决你的问题。

您的代码有更正:

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