1

Llevo algún tiempo aprendiendo de forma autodidacta Python y estoy intentando crear una interfaz gráfica con varias ventanas. Tengo una ventana principal con 3 botones que al presionar me crea otra ventana con otras opciones (aun en construcción...) pero por el momento me minimiza la principal con iconify() pero me gustaría que al cerrar la nueva ventana abierta volviera a aparecer la principal, como también no me dejara crear mas de 1 ventana secundaria. Me refiero, que si ya hay 1 ventana secundaria (de ruleta, blackjack o poker) no me dejara crear otra sin cerrar esta última. Espero haberme explicado bien. No se si es la forma adecuada y probablemente el código no esté escrito de una forma correcta pero aquí os dejo el código de la ventana principal y el de 1 secundaria, pues las 3 secundarias mas o menos tienen lo mismo:

Ventana principal

from tkinter import *
from Ventana_ruleta import VentanaRuleta
from Ventana_bj import VentanaBlackjack
from Ventana_pk import VentanaPoker

class VentanaPrincipal:

    def __init__(self):

        #---Creamos y configuramos la ventana principal
        self.ventana_inicio = Tk()
        self.ventana_inicio.title("Ventana Principal")
        self.ventana_inicio.geometry("650x400")
        self.ventana_inicio.resizable(0,0)
        
        #---Creamos el frame con el titulo

        self.frame_titulo = Frame(self.ventana_inicio)
        self.frame_titulo.pack(side=TOP)
        self.frame_titulo.config(width=650,height=125)
        self.frame_titulo.pack_propagate(False) #Le decimos al Frame que no se amolde al label

        #---Creamos el Label del titulo

        self.label_titulo = Label(self.frame_titulo, text="Practicas Croupier")
        self.label_titulo.pack(anchor = CENTER)
        self.label_titulo.config(font=("Verdana", 32))
        self.label_titulo.config(padx=45, pady=45)

        #---Creamos el Frame con el subtítulo

        self.frame_subtitulo = Frame(self.ventana_inicio)
        self.frame_subtitulo.pack()
        self.frame_subtitulo.config(width=650, height=75)
        self.frame_subtitulo.pack_propagate(False)

        #---Creamos el Label del subtitulo

        self.label_subtitulo = Label(self.frame_subtitulo, text="Selecciona el juego")
        self.label_subtitulo.pack(anchor=CENTER)
        self.label_subtitulo.config(font=("Courier New", 24))
        self.label_subtitulo.config(padx=25, pady=25)

        #---Creamos la funcion de los botones

        def llama_ventana_ruleta():
            self.ventana_inicio.iconify()
            self.ventana_ruleta = VentanaRuleta()
        
        def llama_ventana_bj():
            self.ventana_inicio.iconify()
            self.ventana_bj = VentanaBlackjack()
        
        def llama_ventana_pk():
            self.ventana_inicio.iconify()
            self.ventana_pk = VentanaPoker()
        
        #---Creamos los botones

        self.boton_ruleta = Button(self.ventana_inicio, width=25, height=5, text="Ruleta", command = llama_ventana_ruleta)
        self.boton_bj = Button(self.ventana_inicio, width=25, height=5, text="BlackJack", command = llama_ventana_bj)
        self.boton_pk = Button(self.ventana_inicio, width=25, height=5, text="Poker", command = llama_ventana_pk)
        self.boton_ruleta.place(x=30,y=250)
        self.boton_bj.place(x=230, y=250)
        self.boton_pk.place(x=430, y=250)


        self.ventana_inicio.mainloop()

vp = VentanaPrincipal()

Ventana secundaria

from tkinter import *


class VentanaRuleta:

    def __init__(self):

        #---Creamos la ventana de ruleta
        self.v_ruleta = Tk()
        self.v_ruleta.title("Ruleta Americana")
        self.v_ruleta.geometry("650x400")
        self.v_ruleta.resizable(0,0)
        
         #---Creamos el frame con el titulo

        self.frame_titulo = Frame(self.v_ruleta)
        self.frame_titulo.pack(side=TOP)
        self.frame_titulo.config(width=650,height=115)
        self.frame_titulo.pack_propagate(False) #Le decimos al Frame que no se amolde al label
        self.frame_titulo.config(relief="sunken", bd=10)
        

        #---Creamos el label con el titulo

        self.label_subtitulo = Label(self.frame_titulo, text="Selecciona el tema a practicar o consultar")
        self.label_subtitulo.place(x=5,y=20)
        self.label_subtitulo.config(font=("Courier New", 18))
        self.label_subtitulo.config(padx=15, pady=15)
        
        
        #---Creamos el frame de botones

        self.frame_botones = Frame(self.v_ruleta)
        self.frame_botones.pack()
        self.frame_botones.config(width=650,height=300)

        #---Creamos botones

        self.boton_volver = Button(self.frame_botones, width = 17, height=2, text="Volver")
        self.boton_vecinos = Button(self.frame_botones, width = 17, height = 3, text="Vecinos")
        self.boton_figuras = Button(self.frame_botones, width = 17, height = 3, text="Figuras")
        self.boton_examen = Button(self.frame_botones, width = 17, height = 3, text="Examen")
        self.boton_calculadora = Button(self.frame_botones, width = 17, height = 3, text="Calculadora")
        
        #---Colocamos los botones

        self.boton_vecinos.grid(row = 0, column = 0)
        self.boton_examen.grid(row = 2, column = 0)
        self.boton_volver.grid(row = 1, column = 1)
        self.boton_figuras.grid(row = 0, column = 2)
        self.boton_calculadora.grid(row = 2, column = 2)

        #---Les damos distancia a los botones
        self.boton_vecinos.config(pady=20, padx=20, bd=5)
        self.boton_examen.config(pady=20, padx=20, bd=5)
        self.boton_volver.config(pady=20, padx=20, bd=5)
        self.boton_figuras.config(pady=20, padx=20, bd=5)
        self.boton_calculadora.config(pady=20, padx=20, bd=5)



        #self.v_ruleta.mainloop()

Espero que no se vean muchas barbaridades y no asuste mucho el código, pido disculpas de antemano... jajajajaja Un saludo y muchas gracias!

1 respuesta 1

1

Primero, unas observaciones:

  • Por lo general evita usar más de una instancia de tkinter.Tk en una aplicación. Cada instancia genera su propio intérprete TCL y su mainloop, aparte de poder provocar problemas, es ineficiente. Usa tkinter.Toplevel para generar ventanas secundarias.

  • El inicializador de una clase (__init__) debe retornar inmediatamente una vez incializada la instancia, nos es buena práctica colocar ciclos infinitos como el mainloop en dicho método.

  • En vez de definir las callbacks en el propio inicializador como clausuras hazlas métodos de instancia directamente.

  • Por lo general, usar start/wildcard para importar (from modulo inmport *) es considerado una mala práctica. Facilita el solapamiento inavertido de nombres entre ambos espacios de nombres (pudiendo causar bugs a veces difíciles de detectar), dificultan la legibilidad del código y se puebla el espacio de nombres global sin necesidad.

  • En lo personal prefiero derivar de tkinter.Frame para construir las diferentes partes de una app, luego al final se compone la aplicación distanciando los distintos frames como y cuando queramos. La ventaja es que podremos reutilizar dichas clases dónde queramos (uno de las grandes ventajas de la POO), sin dejar la clase encorsetada a ser una ventana. Es siempre buena idea aplazar la especialización para el final todo lo que podamos.

Dicho ésto, para detectar el cierre de la ventana mediante el botón de la barra de título (gestor de ventanas del sistema operativo de turno) hay que hacer uso del llamado "protocol handlers".

Para evitar que se puedan abrir más ventanas secundarias tienes varias opciones:

Deshabilitar los botones

Una opción es deshabilitar los botones que permiten generar la ventana secundaria, cuando la ventana secundaria se cierre los habilitamos de nuevo:

ventana_ruleta.py
import tkinter as tk


class VentanaRuletaFrame(tk.Frame):

    def __init__(self, parent, *args, **kwargs):
        super().__init__(parent,  *args, **kwargs)
        
        self.parent = parent
        
        #---Creamos el frame con el titulo
        self.frame_titulo = tk.Frame(self)
        self.frame_titulo.pack(side=tk.TOP)
        self.frame_titulo.config(width=650,height=115)
        self.frame_titulo.pack_propagate(False)
        self.frame_titulo.config(relief="sunken", bd=10)
        
        #---Creamos el label con el titulo
        self.label_subtitulo = tk.Label(
            self.frame_titulo,
            text="Selecciona el tema a practicar o consultar", 
            font=("Courier New", 18), padx=15, pady=15, 
            )
        self.label_subtitulo.place(x=5, y=20)
        
        #---Creamos el frame de botones
        self.frame_botones = tk.Frame(self, width=650, height=300)
        self.frame_botones.pack() 

        #---Creamos botones
        self.boton_volver = tk.Button(
            self.frame_botones,  text="Volver",
            width=17, height=2, pady=20, padx=20, bd=5, 
            command=self.volver
            )
        self.boton_vecinos = tk.Button(
            self.frame_botones, text="Vecinos", 
            width=17, height=2, pady=20, padx=20, bd=5
            )
        self.boton_figuras = tk.Button(
            self.frame_botones, text="Figuras", 
            width=17, height=2, pady=20, padx=20, bd=5
            )
        self.boton_examen = tk.Button(
            self.frame_botones, text="Examen",
            width=17, height=2, pady=20, padx=20, bd=5
            )
        self.boton_calculadora = tk.Button(
            self.frame_botones, text="Calculadora", 
            width=17, height=2, pady=20, padx=20, bd=5
            )
            
        #---Colocamos los botones
        self.boton_vecinos.grid(row=0, column=0)
        self.boton_examen.grid(row=2, column=0)
        self.boton_volver.grid(row=1, column=1)
        self.boton_figuras.grid(row=0, column=2)
        self.boton_calculadora.grid(row=2, column=2)

    def volver(self):
        self.event_generate("<<on_come_back>>")
        

class VentanaRuleta(tk.Toplevel):

    def __init__(self, parent, *args, **kwargs):
        super().__init__(parent,  *args, **kwargs)
        self.parent = parent
        
        #---Creamos la ventana de ruleta
        self.title("Ruleta Americana")
        self.geometry("650x400")
        self.resizable(0, 0)
        self.main_frame = VentanaRuletaFrame(self)
        self.main_frame.pack(expand=True, fill=tk.BOTH)
        self.protocol("WM_DELETE_WINDOW", self.on_close)
        self.main_frame.bind("<<on_come_back>>", self.on_close)
        
    def on_close(self, *args):
        self.event_generate("<<on_close>>")
        self.destroy()



if __name__ == "__main__":
    VentanaRuletaFrame().mainloop()
main.py
import  tkinter as tk

from ventana_ruleta import VentanaRuleta
from ventana_bj import VentanaBlackjack
from ventana_pk import VentanaPoker


class VentanaPrincipalFrame(tk.Frame):

    def __init__(self, parent, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.parent = parent

        #---Creamos el frame con el titulo
        self.frame_titulo = tk.Frame(self)
        self.frame_titulo.pack(side=tk.TOP)
        self.frame_titulo.config(width=650, height=125)
        self.frame_titulo.pack_propagate(False)
        
        #---Creamos el Label del titulo
        self.label_titulo = tk.Label(
            self.frame_titulo, text="Practicas Croupier",
            font=("Verdana", 32), padx=45, pady=45
            )
        self.label_titulo.pack(anchor=tk.CENTER)

        #---Creamos el Frame con el subtítulo
        self.frame_subtitulo = tk.Frame(self, width=650, height=75)
        self.frame_subtitulo.pack()
        self.frame_subtitulo.pack_propagate(False)

        #---Creamos el Label del subtitulo
        self.label_subtitulo = tk.Label(
            self.frame_subtitulo, text="Selecciona el juego", 
            font=("Courier New", 24), padx=25, pady=25
            )
        self.label_subtitulo.pack(anchor=tk.CENTER)

        #---Creamos los botones
        self.boton_ruleta = tk.Button(
            self, width=25, height=5, text="Ruleta",
            command=self.llama_ventana_ruleta
            )
        self.boton_bj = tk.Button(
            self, width=25, height=5, text="BlackJack",
            command=self.llama_ventana_bj
            )
        self.boton_pk = tk.Button(
            self, width=25, height=5, text="Poker",
            command=self.llama_ventana_pk
            )
        self.boton_ruleta.place(x=30, y=250)
        self.boton_bj.place(x=230, y=250)
        self.boton_pk.place(x=430, y=250)

    def llama_ventana_ruleta(self):
        self._vent_sec = VentanaRuleta(self.parent)
        self._deshabilitar_interfaz()
        self._vent_sec.bind("<<on_close>>", self._habilitar_interfaz)
        
    def llama_ventana_bj(self):
        self._vent_sec = VentanaBlackjack(self.parent)
        self._deshabilitar_interfaz()
        self._vent_sec.bind("<<on_close>>", self._habilitar_interfaz)
    
    def llama_ventana_pk(self):
        self._vent_sec = VentanaPoker(self.parent)
        self._deshabilitar_interfaz()
        self._vent_sec.bind("<<on_close>>", self._habilitar_interfaz)
        
    def _deshabilitar_interfaz(self, *args):
        self.boton_ruleta.config(state="disabled")
        self.boton_bj.config(state="disabled")
        self.boton_pk.config(state="disabled")
        self.parent.iconify()
        
    def _habilitar_interfaz(self, *args):
        self.boton_ruleta.config(state="normal")
        self.boton_bj.config(state="normal")
        self.boton_pk.config(state="normal")
        self.parent.deiconify()


if __name__ == "__main__":
    #---Creamos y configuramos la ventana principal
    ventana_inicio = tk.Tk()
    ventana_inicio.title("Ventana Principal")
    ventana_inicio.geometry("650x400")
    ventana_inicio.resizable(0, 0)
    VentanaPrincipalFrame(ventana_inicio).pack(expand=True, fill="both")
    ventana_inicio.mainloop()

Deshabilitar la ventana pricipal al completo - Diálogos modales

En vez de seabilitar solo los botones, puedes hacer que cualquier interaaciión con la entan principal sea procesada por la sencundaria, es decir, hacer de la secundaria un diálogo modal. Eso se consigue con el método grab_set.

main.py/VentanaPrincipalFrame
    def _deshabilitar_interfaz(self, *args):
        self.parent.iconify()
        self._vent_sec.grab_set()
        
    def _habilitar_interfaz(self, *args):
        self.parent.deiconify()
        

Ocultar la ventana principal completamente

En vez de solo minimizarla, podemos hacer que directamente desaparezca temporalmente. En vez de iconify usaremos withdraw:

main.py/VentanaPrincipalFrame
    def _deshabilitar_interfaz(self, *args):
        self.parent.withdraw()
    
    def _habilitar_interfaz(self, *args):
        self.parent.deiconify()

  • En las dos últimas opciones ni el resto del módulo ni el código de las ventanas secundarias cambian con respecto al primero, solo los dos métodos apuntados.

  • Hay varios métodos para interactuar con la ventana principal desde la secundaria, he optado por usar un evento.

  • He asociado el botón Volver a la misma callback que el cierre de la ventana mediante el botón de cierre del administrador de ventanas. No se si quieres éste comportamiento.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.