¿Cómo posicionar los diseños en tkinter?

Me gustaría hacer la siguiente GUI .. cada clase de pitón fue hecho y trabajar bien con el nombre sugerido a continuación.

enter image description here

Por ejemplo, la clase relacionada con elementos_estructura parece

class Elements_Structure():
    def __init__(self, root):
        super(Elements_Structure, self).__init__(root)
        self.create_GUI()

    def create_GUI(self):
        label = Label(self, text="Elements Structure", font=("Arial",12)).grid(row=0, sticky=W)
        cols = ('L#', 'Layer Name', 'Material', 'Refractive Index', 'Thickness', 'Unit')
        listBox = Treeview(self, columns=cols, show='headings')

y el código de entrada principal se ve como,

from tkinter import *
from components.elements_structure import *
from components.emission_layer import *
from components.emission_zone_setting import *
from components.file_tab import *
from components.logo_image import *


def main(root):
    top_frame = Frame(root, width=1980, height=780).grid(rowspan=4, columnspan=4)
    bottom_frame = Frame(root, width=1980, height=230).grid(columnspan=4)

    elements_structure_graph = Frame(top_frame, width=480, height=780).grid(row=0, column=0, rowspan=4)
    elements_structure = Frame(top_frame, width=960, height=690).grid(row=0, column=1, rowspan=3, columnspan=2)

    logo_image = Frame(top_frame, width=480, height=230).grid(row=0, column=2)
    logo_properties = Frame(top_frame, width=480, height=230).grid(row=1, column=2)
    logo_execute = Frame(top_frame, width=480, height=230).grid(row=2, column=2)

    emission_layer = Frame(top_frame, width=1440, height=100).grid(row=2, column=2, colspan=3)
    emission_layer_graph = Frame(bottom_frame, width=480, height=290).grid(row=0, column=0)

    emission_zone_setting = Frame(bottom_frame, width=480, height=290).grid(row=0, column=2)
    emission_zone_setting_graph = Frame(bottom_frame, width=480, height=290).grid(row=0, column=1)

    logo_project_info = Frame(bottom_frame, width=480, height=290).grid(row=0, column=3)

    root.title("JooAm Simulator")
    root.geometry('{}x{}'.format(1920, 1080))
    root.mainloop()

if __name__ == '__main__':
    root = Tk()
    File_Tab(root)
    main(root)

Pero me pareció perder el vínculo entre la clase y el objeto de la ventana del tkinter.

¿Cómo puedo hacer la estructura anterior con la biblioteca tkinter?

¡Gracias por adelantado!

Pregunta hecha hace 3 años, 5 meses, 0 días - Por logicluminary


3 Respuestas:

  • Hay mucho que tratar aquí. No puede funcionar en el código sin el archivo de componentes. La mayoría en lo que está en la principal debe ser en crear_ GUI. Me gusta empezar con algo como: clase OLED_Display: def init(self, master): self.master = master auto.frame = tk.Frame(self.master) bg_color='light green ' self.button1 = tk.Button(self.frame, text = 'Constants', ancho = 35, comando = 'ANY USER FUNCTION', bg=bg_color) Puede probar desde allí o proporcionar más información.

    Respondida el Dec 16, 2020 a las 09:43 - por daniel1

    Votos positivos: 0 | Votos negativos: 0

  • El problema en tu código radica en la forma en que estás creando los Frames y asignándolos a las variables top_frame, bottom_frame, etc. En Python, cuando utilizas el método grid() en la misma línea en la que creas el Frame, el resultado de grid() será None y no el objeto Frame en sí. Por lo tanto, top_frame, bottom_frame, etc. serán None en lugar de los Frames que esperas.

    Para solucionar esto, debes separar la creación de los Frames de su posicionamiento utilizando grid(). Aquí te muestro un ejemplo de cómo hacerlo corrigiendo ese aspecto:

    python
    def main(root):
        top_frame = Frame(root, width=1980, height=780)
        top_frame.grid(rowspan=4, columnspan=4)
    
        bottom_frame = Frame(root, width=1980, height=230)
        bottom_frame.grid(columnspan=4)
    
        elements_structure_graph = Frame(top_frame, width=480, height=780)
        elements_structure_graph.grid(row=0, column=0, rowspan=4)
    
        elements_structure = Frame(top_frame, width=960, height=690)
        elements_structure.grid(row=0, column=1, rowspan=3, columnspan=2)
    
        

    Aquí deberías hacer lo mismo para los demás Frames

    root.title("JooAm Simulator") root.geometry('{}x{}'.format(1920, 1080)) root.mainloop() if __name__ == '__main__': root = Tk() File_Tab(root) main(root)

    Al hacer estos cambios, los Frames serán creados y almacenados en las variables correspondientes de forma adecuada, permitiendo que interactúes con ellos como se espera en tu código.

    Respondida el Dec 17, 2020 a las 09:42 - por Gpt

    Votos positivos: 0 | Votos negativos: 0

  • Para posicionar diseños en Tkinter, puedes utilizar el método grid() o pack(). El método grid() te permite colocar widgets en celdas específicas dentro de una cuadrícula, mientras que pack() coloca widgets uno al lado del otro o uno encima del otro, en función de la orientación especificada.

    Para lograr la estructura GUI que deseas, puedes utilizar el método grid(). Aquí tienes un ejemplo:

    python
    from tkinter import *
    
    root = Tk()
    root.title("JooAm Simulator")
    root.geometry('{}x{}'.format(1920, 1080))
    
    

    Crea los distintos marcos

    top_frame = Frame(root, width=1980, height=780) bottom_frame = Frame(root, width=1980, height=230)

    Coloca los marcos en la ventana principal

    top_frame.grid(rowspan=4, columnspan=4) bottom_frame.grid(columnspan=4)

    Crea los distintos widgets y colócalos en los marcos

    elements_structure_graph = Frame(top_frame, width=480, height=780) elements_structure = Frame(top_frame, width=960, height=690) logo_image = Frame(top_frame, width=480, height=230) logo_properties = Frame(top_frame, width=480, height=230) logo_execute = Frame(top_frame, width=480, height=230) emission_layer = Frame(top_frame, width=1440, height=100) emission_layer_graph = Frame(bottom_frame, width=480, height=290) emission_zone_setting = Frame(bottom_frame, width=480, height=290) emission_zone_setting_graph = Frame(bottom_frame, width=480, height=290) logo_project_info = Frame(bottom_frame, width=480, height=290)

    Coloca los widgets en los marcos utilizando el método grid()

    elements_structure_graph.grid(row=0, column=0, rowspan=4) elements_structure.grid(row=0, column=1, rowspan=3, columnspan=2) logo_image.grid(row=0, column=2) logo_properties.grid(row=1, column=2) logo_execute.grid(row=2, column=2) emission_layer.grid(row=2, column=2, colspan=3) emission_layer_graph.grid(row=0, column=0) emission_zone_setting.grid(row=0, column=2) emission_zone_setting_graph.grid(row=0, column=1) logo_project_info.grid(row=0, column=3)

    Ejecuta el bucle principal de la GUI

    root.mainloop()

    Este código creará los distintos marcos y widgets, y los posicionará en la ventana principal utilizando el método grid().

    Ten en cuenta que puedes personalizar aún más la disposición utilizando opciones de configuración adicionales, como sticky, padx y pady. Consulta la documentación de Tkinter para obtener más información.

    Respondida el Dec 17, 2020 a las 09:50 - por Gemini

    Votos positivos: 0 | Votos negativos: 0