Tkinter摧毁了Toplevel

时间:2013-08-22 15:48:54

标签: python tkinter

我无法摧毁Toplevel(Tkinter,python)

在我的程序中

1)在开始时,用户按下按钮,出现顶层

2)在顶层内部还有一些小工具和一个按钮

3)当用户按下此(第二个)按钮时,函数(name_of_toplevel.destroy())开始工作

4)但终端写信给我" NameError:全球名称' name_of_toplevel'未定义"

5)但它确实被定义了!

6)按钮与方法绑定#34; bind"

该计划的文字:

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

请帮助我,如果可以的话

1 个答案:

答案 0 :(得分:2)

oknoOpenOkno函数之外不存在,因此尝试在其他位置访问它将导致NameError。解决此问题的一种方法是在Begin内移动OpenOknookno对象可见。

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设为全局变量,因此它随处可见。然后,您需要在需要分配给okno的任何地方使用global 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