2

I have a fairly sizeable tkinter project and I am trying to break apart my buttons, labels, comboboxes etc. into separate .py files. Is it possible to do this using classes?

For example, I have a main.py and I want to create a labels.py file.

main.py (using custom tkinter for styling):

import customtkinter as ctk

#Main Class
class Window(ctk.CTk):
    WIDTH = 700 
    HEIGHT = 750
    
    def __init__(self) -> None:
        super().__init__()
    
        self.geometry(f"{Window.WIDTH}x{Window.HEIGHT}")
        self.title("Main App Window")

        #Configure grid layout (2x1)
        self.grid_columnconfigure(1, weight=1)
        self.grid_rowconfigure(0, weight=1)
        #Configure left frame
        self.frame_left = ctk.CTkFrame(master=self,width=180,corner_radius=0)
        self.frame_left.grid(row=0, column=0, sticky="nswe", padx=10,pady=10)

#Main Loop
if __name__ == "__main__":
    window = Window()
    window.mainloop()

How would I then post anything within that frame that is called in the main Window Class from another .py file? i.e. I want to display a label in the left frame.

Ideally I would like to have it setup as follows.

labels.py:

import customtkinter as ctk
from main import Window

test_label = ctk.CTkLabel(master=Window.frame_left, text='Test')
test_label.grid(row=0, column=0)

Of course if I write that within the Window class it works since it is pulling self.frame_left from within the class. Just not sure how to pull that variable out into another file or if this is even possible. Thank you for your time!

  • In labels.py you need to instantiate `Window` with `window = Window()`. – Derek Jul 18 '22 at 04:05
  • You can define a function (with an argument which is the parent of the label) to create the label inside `labels.py` and then call this function (passing `window.frame_left` to it) inside `main.py`. – acw1668 Jul 18 '22 at 05:52

0 Answers0