can anyone explain tkinter in object oriented style where you would have it in a class ?

Dani AI

Generated

The thread question (from ) is a common one: put GUI construction and event handlers inside classes and treat Frames as reusable components. and pointed to example collections; below is a minimal, practical pattern that shows how to organize an OO Tkinter app and why each piece belongs where it does.

import tkinter as tk

class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("OO Tkinter")
        container = tk.Frame(self)
        container.pack(fill="both", expand=True)
        self.frames = {}
        for F in (StartPage, SettingsPage):
            frame = F(container, self)
            frame.grid(row=0, column=0, sticky="nsew")
            self.frames[F.__name__] = frame
        self.show_frame("StartPage")

    def show_frame(self, name):
        self.frames[name].tkraise()

class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        super().__init__(parent)
        tk.Label(self, text="Start").pack()
        tk.Button(self, text="Go", command=lambda: controller.show_frame("SettingsPage")).pack()

class SettingsPage(tk.Frame):
    def __init__(self, parent, controller):
        super().__init__(parent)
        tk.Label(self, text="Settings").pack()
        tk.Button(self, text="Back", command=lambda: controller.show_frame("StartPage")).pack()

if __name__ == "__main__":
    app = App()
    app.mainloop()

Notes and tips: keep widget creation in __init__, put event handlers and state-manipulation methods on the class, and pass a controller reference when frames need to coordinate (as shown). Use StringVar/IntVar for shared state, and avoid mixing pack and grid inside the same container. Tkinter must run on the main thread; use after() or a thread-safe queue to update the GUI from background work. For testability, keep business logic out of widget classes and use small Frame subclasses for composable UI pieces. This pattern scales from small scripts to larger apps and makes it easy to add dialogs (Toplevel), custom widgets (subclass Frame), and navigation between views.

Recommended Answers

All 2 Replies

see vegaseat examples from his sticky thread on gui programming.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.