0

Estuve buscando, pero no encontré un equivalente de JDesktopPane y de los JinternalFrame de Java en Python, estoy necesitando pasar un programa de java el cual cuenta con estos widgets a Python, pero por ahora no encontré una alternativa para poder hacerlo. ¿Cuál es el equivalente de estos widgets para Python?

3
  • Que modulo de interfaz grafica usas en Python?
    – Dante S.
    el 28 feb. 2021 a las 17:44
  • Existen varios modulos de interfaz grafica, cada uno con sus propios widgets. Como Tkinter y Wxpython. Depende que modulo uses, podré darte una respuesta o no. La solución que se me ocurre sirve solo para Tkinter y se poco sobre otros modulos de interfaz grafica. Por eso pregunto.
    – Dante S.
    el 28 feb. 2021 a las 20:07
  • @DanteS. Hola!, bien, error mío, no aclaré el modelo de interfaz grafica que uso. Vengo usando Tkinter todo este tiempo. el 1 mar. 2021 a las 1:30

1 respuesta 1

1

No se nada sobre Java, sin embargo, busqué en Google de que se tratan ambos widgets. Por desgracia, no existe nada equivalente en Tkinter. Sin embargo, te ofresco 3 alternativas.


Alternativa 1: Toplevel

Esto es lo más similar que existe dentro de Tkinter.

Puedes usar un Toplevel, que sería como una ventana aparte, pero si cierras la ventana padre, el Toplevel también se cierra.

Puedes aplicar el método .transient() para hacer que el toplevel siempre esté dibujado sobre su ventana padre y si la ventana padre se minimiza, también lo hará esta ventana. Esto tiene de desventaja que la ventana que crees solo se podrá cerrar, no maximizar ni minimizar.

Puedes hacer que un Toplevel se comporte similar (no igual) a una ventana transient con este código:

from tkinter import *

root = Tk()
top = Toplevel()
top.title("TopLevel")

def trasient():
    if(root.state() == "iconic"):
        top.iconify()
    else:
        top.lift()

    top.after(1, trasient)

Entry(root).pack()

trasient()

Esto te permitiría tener una ventana trasient que se puede maximizar.


Alternativa 2: ttk.Notebook

En lugar de crear ventanas, podrías mostrar cosas especificas según una opción en forma de pestaña. El widget que hace este trabajo se llama ttk.Notebook.


Alternativa 3: Hazlo tu mismo

Puedes crear tu mismo el widget JInternalFrame usando el mágico widget Frame. Esta es la alternativa más compleja de las 3 y la unica compatible con lo que yo considero es una especie de JDesktopPane. Por lo que entendí, un JDesktopPane es una zona en la que los JInternalFrame están pero no pueden salirse de él.

Yo mismo me tomé la molestia de crear un widget básico que puede servir a tu propósito :). Esta imitación de JInternalFrame tiene todos los métodos de un Frame mas otros que me encargo de explicar dentro del código.

import tkinter as tk

class jinternalframe(tk.Frame):
    def __init__(Self, master=None, pad=1, width=200, height=200, close=True, maximise=True, minimisable=True):
        Self.pad = pad
        barbg = "lightblue"

        #Creo el frame donde estará la ventana
        Self.window = tk.Frame(master, bg="black")

        # Creo la barra
        Self.bar = tk.Frame(Self.window, bg=barbg)
        Self._buttons = []

        if(close):
            Self._buttons.append(tk.Button(Self.bar, text="X", bg=barbg, command=Self.window.destroy))
        if(maximise):
            Self._buttons.append(tk.Button(Self.bar, text="□", bg=barbg, command=lambda:Self._resize(master)))
            Self.config_resize()
            Self.maximized = False
        if(minimisable):
            Self._buttons.append(tk.Button(Self.bar, text="-", bg=barbg, command=Self._minimize))
            Self.minimized = False
        
        # Creo la parte de la ventana donde van los widgets
        super().__init__(Self.window)

        Self.geometry()

        # Hago que cuando el usuario mueva el mouse con el boton izquierdo apretado, la ventana se mueva #
        Self.bar.bind("<B1-Motion>", Self._move)
        

    def config_resize(Self, minwidth=200, minheight=100):
        # En esta función puedes darle un tamaño a la ventana cuando no está maximizada #
        Self.minwidth=minwidth
        Self.minheight=minheight
        

    def _move(Self, Event):
        # esta función hace posible que el usuario pueda mover la ventana #
        w = Self.window
        master = w.nametowidget(w.winfo_parent())

        x = w.winfo_x()+Event.x
        y = w.winfo_y()+Event.y

        maxx = master.winfo_width()-w.winfo_width()
        maxy = master.winfo_height()-w.winfo_height()

        # Evito que el JInternalFrame se salga de su "JDesktopPane" #
        if(x < 0):
            x = 0
        elif(x > maxx):
            x = maxx

        if(y < 0):
            y=0
        elif(y > maxy):
            y = maxy


        w.place(x=x, y=y)
        w.update()

        

    def _resize(Self, master):
        # Esta función hace posible maximizar la ventana #
        
        if(Self.maximized):
            Self.geometry(Self.minwidth, Self.minheight)
        else:
            Self.geometry(master.winfo_width(), master.winfo_height(), 0, 0)

        Self.maximized = not Self.maximized
        

    def _minimize(Self):
        # Esta función hace posible minimizar la ventana #
        
        if(Self.minimized):
            Self.window["height"]=Self.tamanoy
        else:
            Self.tamanoy = Self.window.winfo_height()
            Self.window["height"]=Self.bar.winfo_x()+Self.bar.winfo_height()+Self.pad

        Self.minimized = not Self.minimize
        
        
    def geometry(Self, width=200, height=100, x=None, y=None):
        # Con esta función puedes cambiar el tamaño y la posición de tu ventana #
        
        # Si x es None (el usuario no ingresó la posicion x), obtengo la ubicación de la ventana en el eje x. #         
        if(x is None):
            x=Self.window.winfo_x()

        # Lo mismo hago con la posición y #
        if(y is None):
            y=Self.window.winfo_y()
        

        # Ubico la ventana #
        Self.window.place(x=x, y=y)
        
        pad = Self.pad

        # Cambio el tamaño de la ventana y adapto toda la interfaz al nuevo tamaño #
        Self.window.config(width=width, height=height)
        Self.window.update()

        Self.bar.config(width=(width-pad*2), height=20)
        Self.bar.place(x=pad, y=pad)
        Self.bar.update()

        Self.config(width=(width-pad*2), height=(height-Self.bar["height"]-pad*3))
        Self.place(x=pad, y=(Self.bar["height"]+pad*2))

        x = Self.bar["width"]

        for button in Self._buttons:
            button.place(x=9999, y=9999)
            button.update()
            
            x -= button.winfo_width()
            
            button.place(x=x, y=0)

    def acomodar(Self):
        Self.place(width=(Self.window.winfo_width()-Self.pad*2), height=(Self.window.winfo_height()-Self.bar["height"]-Self.pad*3))
        

v=tk.Tk()

# Lo más parecido a un JDesktopPane en Tkinter es un Frame #
JDesktopPane=tk.Frame(width=300, height=300)
JDesktopPane.pack()

subventana = jinternalframe(JDesktopPane)
tk.Entry(subventana).pack()
tk.Entry(subventana).pack()

# Esta función la tendrás que ejecutar cuando posiciones widgets con .pack o .grid, ya que estos le cambian el tamaño al "jinternalframe" #
subventana.acomodar()

Cualquier estilo que le quieras dar, función o mejora es tarea para la casa ;)


Te recomiendo que uses la alternativa 1 o 2 ya que estas cosas ya están hechas y probablemente están mejor diseñadas que mi código en la alternativa 3. Solo por curiosidad, te sirvió mi respuesta? Por cual de las 3 alternativas vas a optar si fue así?

1

Tu Respuesta

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

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