Python Tkinter Tutorial (Part 2): Implementing Classes for Enhanced Functionality and Structured Organization

Posted by


In part 1 of this Tkinter tutorial series, we covered the basics of creating a simple GUI using Tkinter in Python. In this part 2, we will explore how to use classes to create more sophisticated GUIs with better functionality and organization.

Classes in Python allow you to encapsulate data and functionality into a single unit. By using classes in your Tkinter applications, you can create reusable components, organize your code more efficiently, and easily extend and modify your GUI as needed.

In this tutorial, we will create a simple calculator GUI using Tkinter and classes. We will create a Calculator class that encapsulates all the functionality of our calculator, such as adding numbers, subtracting numbers, etc. Let’s get started!

Step 1: Import tkinter and create the main window

First, we need to import the Tkinter module and create a main window for our calculator application. Add the following code to your Python script:

import tkinter as tk

root = tk.Tk()
root.title("Calculator")

Step 2: Create the Calculator class

Next, we will create a Calculator class that encapsulates all the functionality of our calculator. Add the following code to your script:

class Calculator:
    def __init__(self, master):
        self.master = master
        self.result = tk.StringVar()
        self.result.set("0")

        self.display = tk.Entry(self.master, width=15, textvariable=self.result, font=('Arial', 12))
        self.display.grid(row=0, column=0, columnspan=4)

        self.create_buttons()

    def create_buttons(self):
        buttons = [
            '7', '8', '9', '/',
            '4', '5', '6', '*',
            '1', '2', '3', '-',
            'C', '0', '=', '+'
        ]

        row = 1
        col = 0

        for button_text in buttons:
            tk.Button(self.master, text=button_text, width=5, height=2,
                      command=lambda x=button_text: self.on_button_click(x)).grid(row=row, column=col)

            col += 1
            if col > 3:
                col = 0
                row += 1

    def on_button_click(self, text):
        if text == 'C':
            self.result.set("0")
        elif text == '=':
            try:
                self.result.set(eval(self.result.get()))
            except:
                self.result.set("Error")
        else:
            if self.result.get() == "0":
                self.result.set(text)
            else:
                self.result.set(self.result.get() + text)

Step 3: Instantiate the Calculator class and run the main loop

Finally, we need to instantiate the Calculator class and run the main loop of our Tkinter application. Add the following code to your script:

calculator = Calculator(root)

root.mainloop()

That’s it! You have now created a simple calculator GUI using Tkinter and classes. By using classes, you can encapsulate the functionality of your GUI components and create more organized and efficient code.

Feel free to extend and modify the Calculator class to add more advanced features and functionality to your calculator application. Tkinter offers a wide range of GUI components and events that you can leverage to create more sophisticated GUIs.

I hope you found this Tkinter tutorial helpful and informative. Stay tuned for more tutorials on using Tkinter in Python to create powerful and dynamic GUI applications!

0 0 votes
Article Rating
44 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@coreyms
1 month ago

I'm going to be continuing this Tkinter series and also getting into other GUI Frameworks as well. I'm going to have a couple of one-off videos until the next Tkinter one is dropped, but it shouldn't be too long. These other videos will include tutorials on Pathlib, Setting up my new Website, etc. Hope yall find this helpful!

@LeopoldCyril-v5p
1 month ago

Taylor Kimberly White Sandra Jones Richard

@drendelous
1 month ago

Corey, pls consider getting to the point right at the beginning of a video.. beginners like myself spend so much time on people going round and round. if they watch a video they will sort out part 1 and other stuff on their own perfectly

@samincgs
1 month ago

Hey Corey, Thank you for covering tkinter and teaching us everything in such a concise and easy to understand way. you do so much for the community and I am super grateful! Just a suggestion but could you cover a module called custom_tkinter as one of the episodes, it has all the basic functionalities of tkinter but has some more built in styling and a more modern look. Thanks as always!

@peterlakos4108
1 month ago

I write GUI applicaitons occasionally, so this is wirth gold for me for sure. I also liked the walkthrough at the end, that might be a good practice at least for the more complicated stuff.

By the way, this is the single best Python tutorial channel around.

Nothing else to add. 🙂

@Archi4me
1 month ago

Dear Python Team,

I hope this message finds you well.

I would like to suggest a feature enhancement for the Python development tools. It would be incredibly useful if there was an automatic spellcheck and correction feature integrated into the development environment. This would help users quickly identify and correct typos, improving coding efficiency and reducing errors.

Thank you for considering this suggestion. I look forward to any updates regarding this potential feature.

Best regards,
[Mohaddese]

@kylenicholson659
1 month ago

A question I don't see addressed very often: When is a desktop / GUI application preferable to a web application? I have ideas in mind for things I want to build, but I often get stuck at the point of figuring out which option makes more sense. Thanks for the tutorial!

@saifsaket8486
1 month ago

Hello Corey Schafer you are the best Python and Data Science Teacher i’ve seen ever… your way of explaining make the difficult consents as a game, I wish you start a new YouTube series about the machine learning🔥🔥,like to help him see the comment

@salarghaffarian4914
1 month ago

Awesome as always!

@ckks0nyoutube
1 month ago

I need to better understand rowconfigure and columnconfigure, please help

@JoeBurnett
1 month ago

Glad to see you posting videos again!

@EslamTawfig
1 month ago

Very interesting video for real. I've learned a lot.

@kermitdaphrogge525
1 month ago

Yesterday I purchased a pyqt6 course after everyone told me its better than tkinter.
Now that I've seen your videos for years, I'm confused which way to go.

Which one should I go with?
All that matters to me is a good framework

@jaynj908
1 month ago

I have a book on Tkinter and it does say to use classes

@MuhammadFaisal-sx5gl
1 month ago

King is back ✨❤️

@meta_ai
1 month ago

when I was struggling 6 years ago and wanted to learn programming you were the one I learned Django from. Now I am at a place where I would never have imagined in my life. Thanks for all the help and videos. Love from Pakistan.

@SP-db6sh
1 month ago

Live to see your video bcz of lucid n live explanations of complex topics ! Your are the tech Guru !
Expecting this series on taipy or Pyors or tutorials on rust , like more relevant to updated topics in 2024.

@ivolol
1 month ago

Very happy to see this continuing, wish you the best and inspiration for it!

@giorgihaj
1 month ago

I am so happy you are back! You are the best teacher I have ever seen thank you for keeping on YouTube❤❤❤

@nikhilt3755
1 month ago

gui programming is so clean and perfect with oops.
i am currently doing small login with sessions tokens in python flet gui. once i started writing classes for gui components i needed in separate files, it became easy as i just need to insert an object in the main page's container.