Building Cloud Expertise with centron - Our Tutorials

Whether you are a beginner or an experienced professional, our practical tutorials provide you with the knowledge you need to make the most of our cloud services.

Advanced Application Development with Tkinter Classes

If you already have experience with Tkinter, you know that this module offers many GUI features for creating an application. However, as you develop applications, you’ll quickly realize that there’s more to this module than meets the eye. Tkinter has many hidden features, and one of them is the use of classes within the module.

Setting up the Tkinter Module

First and foremost, you don’t need to install any additional modules, as the tkinter module is part of the standard Python library. However, in this article, we will cover a slightly more advanced form of the tkinter module, so we recommend mastering the basics first.

Once you’ve mastered the basics, we can start working with the tkinter module. To work with classes, we first need to import the tkinter module.

# Import the tkinter module
import tkinter as tk

# Use for GUI styling
from tkinter import ttk

We will also import the ttk package separately to make its usage easier.

Working with Classes in Tkinter

Let’s understand how to work with classes in Tkinter. The functionality of the application is quite simple. First, we create a root window on which we place a single frame. To make it look like an application with different windows, we also create a function that switches between the frames. This gives the user the illusion of being redirected to another window/tab, even though they are actually just switching between frames. The frames we’ll be working with are MainPage, SidePage, and CompletionScreen. The method we’ll use to switch between them is the `show_frame()` method.

Working on the Code

Let’s start by creating a base class from which we will access all other classes/frames.

# Inherit from the Tk class
class TestClass(tk.Tk):

By inheriting from the `tk.Tk` class, we can work with components present in the `Tk()` class.

1. Initializing the Classes

To initialize the class, we use the `__init__` function. This creates a method that runs itself when we create an object from the class. Similarly, we also initialize the class using `tk.Tk __init__`.

import tkinter as tk
from tkinter import ttk

class Windows(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        # Add a title to the window
        self.wm_title("Test Application")

        # Create a frame and assign it the container
        container = tk.Frame(self, height=400, width=600)
        # Set the area where the frame is packed in the root window
        container.pack(side="top", fill="both", expand=True)

        # Configure the position of the container with grid
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        # We are now creating a dictionary of frames
        self.frames = {}
        # We will create the frames themselves later, but already add the components to the dictionary
        for F in (MainPage, SidePage, CompletionScreen):
            frame = F(container, self)

            # The Windows class serves as the root window for the frames
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        # Use a method to switch frames
        self.show_frame(MainPage)

2. Creating a Method to Change the View Frames

Now that we have created the `__init__` method and defined the frames, we can create a method that changes the displayed frame.

def show_frame(self, cont):
        frame = self.frames[cont]
        # Raise the current frame to the top
        frame.tkraise()

3. Creating Multiple Classes for Frames

Now, we create different classes that act as frames and can be switched using the `show_frame()` method.

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" to call the show_frame() method as a lambda function
        switch_window_button = tk.Button(
            self,
            text="Switch to Side View",
            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 View")
        label.pack(padx=10, pady=10)

        switch_window_button = tk.Button(
            self,
            text="Switch to Completion View",
            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="Back to Main Page",
            command=lambda: controller.show_frame(MainPage),
        )
        switch_window_button.pack(side="bottom", fill=tk.X)

Unlock the Power of Tkinter: Start Your Python GUI Journey with a Free Trial Today!

Experience seamless GUI development with Python and Tkinter. Start your free trial now and unleash the potential of advanced application development!

Try for free!