Skip to content Skip to sidebar Skip to footer

How To Use Destroy In These Cases

ran into another problem when handling modules. I can't get 'destroy' to work. I want to open with a button and close with another button the toplevel window. Here is a little code

Solution 1:

It is because top is a local variable inside importar() function.

Use instance variable self.top instead:

class PRUEBA:
    def __init__(self, *args):
    
        ventana_principal = tk.Tk()        
        ventana_principal.geometry("600x600") 
        ventana_principal.config(bg="blue") 
        ventana_principal.title("PANTALLA PRINCIPAL") 
    
        def importar():
            from dos import toplevel
            self.top = toplevel(ventana_principal)  

        boton = tk.Button(ventana_principal, text="open", command=importar)
        boton.pack()  
        boton1 = tk.Button(ventana_principal, text="close", command=lambda: self.top.destroy())
        boton1.pack()

Note that you need to cater the situation where open button is clicked more than once before close button is clicked. Then there will be two or more toplevel windows and close button can only close the last open window.

Also you cannot click close button before open button.


Post a Comment for "How To Use Destroy In These Cases"