Tutorial

Advanced Tkinter: Working with Classes

Published on August 4, 2022
author

Meghna Gangwar

Advanced Tkinter: Working with Classes

Today, we’ll be working with classes in Tkinter. If you’ve worked with Tkinter before, you probably know that there’s a whole lot of GUI features that you can use to create an application.

But, while creating applications, you quickly realize that there’s more to the module than what meets the eye.

There’s a lot of hidden features in tkinter, and one of them is the method to use classes in the module.

Setting up the Tkinter Module

There’s no need to install any module, as the tkinter module is a part of the standard Python library.

However, this article will be dealing with a slightly advanced form of the tkinter module, so, it is recommended to go through the beginner series.

So before you move ahead, don’t forget to read through the basic tutorials on TKinter here:

If you’re done with the basic tutorials, let’s get into working with the tkinter module.

In order to work with classes, we’ll need to import the tkinter module.

# Importing the tkinter module
import tkinter as tk

# Used for styling the GUI
from tkinter import tkk

We’ll also be importing the ttk package separately for ease of use.

Working with Classes in Tkinter

Let us understand how to work with classes in Tkinter. The way the application works is pretty simple.

We first create a root window, on top of which we place a single frame.

In order to make it seem like an application with different windows, we’ll also create a function that switches from one frame to another.

This gives the user an illusion that they are being redirected to a different window/tab, but, are really just switching between frames.

The Frames we’ll be working with are the MainPage, SidePage and CompletionScreen.

The method that we will use for switching between them is the show_frame() method.

Working on the Code

Let’s create a base class from which we’ll access all the other classes/frames to start off.

# Allowing us to extend from the Tk class
class testClass(tk.Tk):

Extending from the tk.Tk class allows us to work with components that are present in the Tk() class.

1. Initializing the classes

In order to initialize the class, we use the __init__ function. This creates a method that runs itself when we form an object from the class.

In a similar fashion, we are initializing the class through the tk.Tk __init__ as well.

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)

2. Creating a Method to Switch View Frames

Now that we’ve created the __init__ and have also specified the Frames that we’re going to use, we can create a method that switches the frame that we are viewing

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

3. Creating Multiple Classes for Frames

Now, we create different classes that act as Frames that are 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 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 you’ve noticed, these classes are added to the main class, using the self.frames variable.

I’ll be keeping the commands to implement the classes in a __name__=="main", but, you can use it directly as well.

if __name__ == "__main__":
    testObj = windows()
    testObj.mainloop()

Moving Forward

We are now done with defining the classes and the methods, and can run this script.

This should present you with a tiny window which allows you to switch between frames with the click of a button.

On a higher level, you can even have the functionality to switch between frames in a menu bar on the top of the application.

Conclusion

Working with classes in tkinter module, opens up a lot of doors to working on and creating new applications.

We’ve worked on quite a bit of code today, and just so we’re on the same page, here’s the gist!

If you wish to look at a live example, Check out my project Eisen’s Tickets, which implements a lot of Tkinter features including classes, and works using SQLite3.

References

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Meghna Gangwar

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.