Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Here's an implementation of working with Classes in Tkinter.
import tkinter as tk
from tkinter import ttk
class windows(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# Adding a title to the window
self.wm_title("Test Application")
# creating a frame and assigning it to container
container = tk.Frame(self, height=400, width=600)
# specifying the region where the frame is packed in root
container.pack(side="top", fill="both", expand=True)
# configuring the location of the container using grid
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
# We will now create a dictionary of frames
self.frames = {}
# we'll create the frames themselves later but let's add the components to the dictionary.
for F in (MainPage, SidePage, CompletionScreen):
frame = F(container, self)
# the windows class acts as the root window for the frames.
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
# Using a method to switch frames
self.show_frame(MainPage)
def show_frame(self, cont):
frame = self.frames[cont]
# raises the current frame to the top
frame.tkraise()
class MainPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Main Page")
label.pack(padx=10, pady=10)
# We use the switch_window_button in order to call the show_frame() method as a lambda function
switch_window_button = tk.Button(
self,
text="Go to the Side Page",
command=lambda: controller.show_frame(SidePage),
)
switch_window_button.pack(side="bottom", fill=tk.X)
class SidePage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="This is the Side Page")
label.pack(padx=10, pady=10)
switch_window_button = tk.Button(
self,
text="Go to the Completion Screen",
command=lambda: controller.show_frame(CompletionScreen),
)
switch_window_button.pack(side="bottom", fill=tk.X)
class CompletionScreen(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Completion Screen, we did it!")
label.pack(padx=10, pady=10)
switch_window_button = ttk.Button(
self, text="Return to menu", command=lambda: controller.show_frame(MainPage)
)
switch_window_button.pack(side="bottom", fill=tk.X)
if __name__ == "__main__":
testObj = windows()
testObj.mainloop()
@anna-smith97
Copy link

anna-smith97 commented Aug 1, 2021

This code was well commented and helpful-- thank you for posting.

@dat-adi
Copy link
Author

dat-adi commented Aug 1, 2021

Glad you like it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment