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.
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.
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.
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.
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)
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()
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()
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.
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.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
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.
Sign up for Infrastructure as a Newsletter.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.