how to use destroy in these cases

不羁的心 提交于 2021-01-29 15:06:01

问题


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 to apply destroy

# module uno.py

import tkinter as tk 
class PRUEBA:
    def __init__(*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
            top = toplevel(ventana_principal)  

        boton = tk.Button (ventana_principal , text = "open" , command = importar)
        boton.pack ( )  
        boton1 = tk.Button (ventana_principal , text = "close" , command = top.destroy) #does not work destroy
        boton1.pack ( )
    
        ventana_principal.mainloop()  
PRUEBAS = PRUEBA ()

#module dos.py

import tkinter as tk 

class toplevel(tk.Toplevel):
     def __init__(self, parent, *args, **kw):
        super().__init__(parent, *args, **kw)
        self.geometry("150x40+190+100")        
        self.resizable(0, 0)
        self.transient(parent)

回答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.



来源:https://stackoverflow.com/questions/63477254/how-to-use-destroy-in-these-cases

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!