简体   繁体   中英

Tkinter destroying a Toplevel

I cannot destroy a Toplevel (Tkinter, python)

In my program

1) in the beginning user presses the button and the toplevel appears

2) inside the toplevel there are some more widgets and one more button

3) when user presses this (second) button, the function (name_of_toplevel.destroy()) start working

4) but then Terminal writes me "NameError: global name 'name_of_toplevel' is not defined"

5) but it really IS defined!

6) buttons are bound with functions with method "bind"

Text of the program:

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

please, help me, if you can

okno doesn't exist outside of the OpenOkno function, so attempting to access it anywhere else will cause a NameError . One way to address this is to move Begin inside OpenOkno , where the okno object is visible.

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

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

You could also use a lambda expression in place of a full function, as an argument to Bind .

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

You could also make okno a global variable, so it will be visible everywhere. You would then need to use the global okno statement anywhere you need to assign to 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM