2013-08-22 77 views
1

我不能破壞的Toplevel(Tkinter的,蟒)Tkinter的銷燬的Toplevel

以我在開始用戶程序

1)按下按鈕和頂層出現

2)頂層內有一些以上小窗口和一個多按鈕

3)當用戶按下該(第二)按鈕時,功能(name_of_toplevel.destroy())開始工作

4)但終端寫我「NameError:全球名稱'name_of_toplevel'未定義」

5)但它確實是定義的!

6)按鈕與方法 「綁定」 計劃的

文本函數約束:

from Tkinter import * 


def Begin(event): 
    okno.destroy() 

def QuitAll(event): 
    exit(0) 

def OpenOkno(event): 
    #print "<ButtonRelease-1> really works! Horray!" 
    okno = Toplevel() 
    okno.title('Question') 
    okno.geometry('700x300') 

    Sign = Label(okno,text = 'Quit the program?', font = 'Arial 17') 
    Sign.grid(row = 2, column = 3) 

    OK = Button(okno, text = 'YES', bg = 'yellow', fg = 'blue', font = 'Arial 17') 
    OK.grid(row = 4, column = 2) 

    OK.bind("<ButtonRelease-1>",QuitAll) 


    NO = Button(okno, text = 'NO', bg = 'yellow', fg = 'blue', font = 'Arial 17') 
    NO.grid(row = 4, column = 4) 

    NO.bind("<ButtonRelease-1>",Begin) 




root = Tk() # main window 'program_on_Python' 

root.title('Program_on_Python') 

root.geometry('400x600') 



knpk = Button(root, text = 'click here!', width = 30, height = 5, bg = 'yellow', fg = 'blue', font = 'Arial 17') 
knpk.grid(row = 2, column = 2) 

knpk.bind("<ButtonRelease-1>",OpenOkno) 

root.mainloop() 

請幫我,如果你能

回答

2

okno不存在外OpenOkno函數,所以試圖在其他地方訪問它將導致NameError。解決此問題的一種方法是在OpenOkno內移動Begin,其中okno對象可見。

def OpenOkno(event): 
    def Begin(event): 
     okno.destroy() 

    #print "<ButtonRelease-1> really works! Horray!" 
    okno = Toplevel() 
    #etc... Put rest of function here 

你也可以使用lambda表達式來代替一個全功能的,作爲參數傳遞給Bind

NO.bind("<ButtonRelease-1>", lambda event: okno.destroy()) 

你也可以讓okno成爲一個全局變量,所以它在任何地方都是可見的。然後,您需要使用global okno語句將需要分配給okno的任何地方。

okno = None 

def QuitAll(event): 
    exit(0) 

def Begin(event): 
    okno.destroy() 

def OpenOkno(event): 

    #print "<ButtonRelease-1> really works! Horray!" 
    global okno 
    #etc... Put rest of function here