Using Classes in Tkinter Advanced Techniques

In today’s session, we will focus on classes in Tkinter. If you have prior experience with Tkinter, you are likely aware of the extensive range of GUI features available for application development.

However, when developing applications, you soon realize that the module has additional complexities beyond what is immediately apparent.

In tkinter, there are numerous concealed features, and among them is the inclusion of the class functionality within the module.

Configuring the Tkinter Module

You don’t have to install any module because the tkinter module is included in the standard Python library.

However, this article will focus on a more advanced version of the tkinter module, so it is suggested that you review the beginner series first.

Before you proceed, make sure you take the time to familiarize yourself with the fundamental tutorials on TKinter available here.

  • Tkinter Part – 1
  • Tkinter Part – 2
  • Tkinter Part – 3

If you have finished the fundamental tutorials, let’s start delving into using the tkinter module.

To utilize classes, we must import the tkinter module.

# Importing the tkinter module
import tkinter as tk

# Used for styling the GUI
from tkinter import tkk

To make things more convenient, we will import the ttk package individually.

How to use Classes in Tkinter.

We will now learn how to use classes in Tkinter. The functioning of the application is quite straightforward.

To start, we establish a main window, where we position a sole frame on its top layer.

To create the illusion of an application having multiple windows, we will additionally develop a function that transitions between various frames.

The user is made to believe that they are being directed to a separate window or tab, but in reality, they are just switching between frames.

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

The way we will switch between them is by utilizing the show_frame() method.

Coding is being worked on.

To begin with, we should establish a fundamental class that will serve as our gateway to access all the remaining classes/frames.

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

By inheriting the tk.Tk class, we gain the ability to interact with elements that exist in the Tk() class.

1. Starting up the classes

To begin the class, we utilize the __init__ function which generates a method that automatically executes when we create an object from the class.

Likewise, we are also initializing the class via the tk.Tk __init__ method.

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. Developing a Technique for Changing View Frames

Once the __init__ is set up and the Frames are selected, we can proceed with developing a function to change the frame being viewed.

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

3. Developing multiple classifications for frames.

Currently, we generate a variety of classes that function as Frames, and these Frames are swapped 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)

You might have observed that the self.frames variable is used to add these classes to the main class.

While I will retain the instructions for implementing the classes under __name__==”main”, you also have the option to use them directly.

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

Advancing

Now that we have finished defining the classes and methods, we are ready to execute this script.

You should see a small window that enables you to easily switch between frames by clicking on a button.

At a higher level, you also have the capability to switch between frames within an application by using a menu bar located at the top.

In summary, to wrap it up…

When utilizing classes in the tkinter module, it allows for numerous possibilities and opportunities in developing and innovating applications.

Today we have been busy with a lot of coding, and to make sure we’re all in agreement, here’s the main idea!

If you want to see it in action, take a look at my project Eisen’s Tickets. It demonstrates various Tkinter features like classes and operates with SQLite3.

Can you provide me with a single alternative to paraphrase the word “References” natively?

  • Tkinter Documentation
  • Tkinter Classes

 

More tutorials

How to utilize sub() and gsub() functions in R(Opens in a new browser tab)

init or Swift initialization in Swift(Opens in a new browser tab)

Spring MVC Controller(Opens in a new browser tab)

jQuery parent() and children() tree traversal functions(Opens in a new browser tab)

Beginners can find a tutorial on Java web applications.(Opens in a new browser tab)

Leave a Reply 0

Your email address will not be published. Required fields are marked *