【问题标题】:Python Tkinter error object has no attributePython Tkinter 错误对象没有属性
【发布时间】:2016-04-17 10:52:57
【问题描述】:

所以我正在制作一个类似于街机游戏的程序。我希望 lableGuess 在单击框架后出现在顶层窗口中,但它给了我这个错误:

AttributeError: 'Window' 对象没有属性 'window'

代码如下:

from tkinter import *
from tkinter import font
import time

class Window(Frame):

    def __init__(self, master):

        Frame.__init__(self, master)
        self.master = master

        master.title("Arcade Games")
        master.geometry("800x600+560+240")

        b = Button(self, text="Guess the number", command=self.new_window)
        b.pack(side="top")
        self.customFont = font.Font(master, font="Heraldica", size=12)

        self.guess_number()

    def new_window(self):

        id = "Welcome to the 'Guess your number' game!\nAll you need to do is follow the steps\nand I will guess your number!\n\nClick anywhere to start!"
        self.window = Toplevel(self.master)
        frame = Frame(self.window)
        frame.bind("<Button-1>", self.guess_number)
        frame.pack()
        self.window.title("Guess the number")
        self.window.geometry("400x300+710+390")
        label = Label(self.window, text=id, font=self.customFont)
        label.pack(side="top", fill="both", padx=20, pady=20)

    def guess_number(self):


        labelGuess = Label(self.window, text="Pick a number between 1 and 10", font=self.customFont)
        time.sleep(2)
        labelGuess.pack(fill=BOTH, padx=20, pady=20)

if __name__ == "__main__":
    root = Tk()
    view = Window(root)
    view.pack(side="top", fill="both", expand=True)
    root.mainloop()

【问题讨论】:

    标签: python tkinter attributeerror


    【解决方案1】:

    在您按下按钮并触发new_window 事件回调之前,可能会调用您在初始化方法中对guess_number 的初始调用。在guess_number 中,您试图将self.window 作为参数传递给Label(),但当时它是未定义的。

    【讨论】:

    • 不是“可能”——“肯定”。它就在__init__self.guess_number()
    【解决方案2】:

    首先,您永远不应该在__init__ 方法之外创建新属性。

    也就是说,Mike 指出了问题的原因:您在 new_window 方法中创建了窗口对象,但没有调用它。

    您必须在调用guess_number 之前调用new_window - 或在另一个内部调用。

    我建议您将window 设置为None 并在__init__ 方法中调用new_window,然后(之后)调用guess_number

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-08
      相关资源
      最近更新 更多