2016-01-12 140 views
1

所以我正在製作一個類似於街機遊戲的程序。我想lableGuess以點擊框架後出現在頂層窗口,但它給了我這個錯誤:Python Tkinter錯誤對象沒有屬性

AttributeError的:「窗口」對象有沒有屬性「窗口」

下面的代碼:

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

回答

3

在初始化方法中初始調用guess_number可能在您按下按鈕並觸發new_window事件回調之前被調用。在guess_number中,您試圖將self.window作爲參數傳遞給Label(),但當時它將不確定。

+0

不是「可能」 - 「絕對」。它就在'__init__'中:'self.guess_number()' –

0

首先,您絕對不應該使用__init__方法創建新屬性。

也就是說,Mike指出了麻煩的原因:你在new_window方法內創建了窗口對象,但沒有調用它。

您必須先致電new_window,然後致電guess_number - 或者打電話給其他人。

我建議你設置windowNone,並呼籲new_window__init__方法,然後(後)調用guess_number

+0

Thanks m8!它確實有幫助! – ToucaN

相關問題