Search code examples
pythontkinterpycharmcustomtkinternew-window

Name "window" is not defined error is coming while executing the mentioned code


Name "window" is not defined error is coming while executing the mentioned code

def create_window():
    window = ctk.CTk()
    window.title("CREATE")
    window.geometry("1789x760")

create_frame = ctk.CTkFrame(window, width=600, height=300)
create_frame.pack()

create_label = ctk.CTkLabel(create_frame, text="Sample")
create_label.pack()

window.mainloop()

Solution

  • You could try this functional approach:

    def populate_window(root_window):
        create_frame = ctk.CTk.Frame(root_window, width=600, height=300)
        create_frame.pack()
        create_label = ctk.CTkLabel(create_frame, text="Sample")
        create_label.pack()
    
    window = ctk.CTk()
    window.title('CREATE')
    window.geometry('1789x760')
    window.mainloop()
    

    This would work, however, you would not be able to reuse the populate_window function easily.

    This Object Oriented approach would allow for more portability and code reuse:

    class Window(ctk.CTkFrame):
        def __init__(self, parent):
            self.parent = parent
            ctk.CTkFrame.__init__(self, self.parent)
            self.pack()
            self.populate_window()
    
        def populate_window(self):
            create_label = ctk.CTkLabel(self, text="Sample")
            create_label.pack()
    
    if __name__ == '__main__':
        root = ctk.CTk()
        root.title("CREATE")
        root.geometry('1789x760')
        window = Window(root)
        root.mainloop()