Reputation: 11
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)
Upvotes: 0
Views: 58
Reputation: 46669
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.
Upvotes: 1