[英]Python Tkinter error object has no attribute
所以我正在制作類似於街機游戲的程序。 我希望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()
您可以在按下按鈕並觸發new_window
事件回調之前調用初始化方法中對guess_number
初始調用。 在guess_number
你試圖將self.window
作為參數傳遞給Label()
但那時它將是未定義的。
首先,您永遠不應該使用__init__
方法創建新屬性。
也就是說, Mike指出了麻煩的原因:你在new_window
方法中創建了window對象,但沒有調用它。
你必須在調用new_window
之前調用guess_number
- 或者在其他內部調用一個。
我建議您將window
設置為None
並在__init__
方法中調用new_window
,然后(之后)調用guess_number
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.