Python GUI Programming With Tkinter

Hey there, fellow tech enthusiasts! It’s finally the second semester of my first year, and it has been quite the challenge. I've started diving deeper into Python, and while the first semester of Python programming was relatively straightforward, I was learning about data types, variables, functions, decision structures, repetition structures, and libraries. I even had the chance to build some really cool projects like a mini-madLib game and a basic calculator.

What is Tkinter?

Tkinter is Python's go-to library for creating Graphical User Interfaces it offers a versatile and user-friendly way to craft GUI applications that are both functional and visually appealing.

Setting up Tkinter:

Before we dive into my project, let's start by ensuring you have Tkinter set up on your machine. If it's not already bundled with your Python installation,

import tkinter as tk

Building the Student Average Calculator App:

The goal of this project is to create an app that makes it easy to calculate students' averages. I'll break down the code below so you can code along with me.

After importing the library, I started defining the function I need to make my calculator take input from students and add three test scores,

def calculate_average():

I also wanted to ensure that the datatype of the resultd was floats because we are dealing with averages, I had a few errors while working on this because I was not specific enough.

def calculate_average():
    try:
        # test results + convert to float
        result1_score = float(result1_entry.get())
        result2_score = float(result2_entry.get())
        result3_score = float(result3_entry.get())

        # Calculate the average
        average = (result1_score + result2_score + result3_score) / 3

        # show average results
        result_label.config(text=f"Your Average Score is: {average:.2f}")
    except ValueError:
        result_label.config(text="Invalid input. This is not correct! Try again.")

Here I used Try Except in order to handle some errors for example if a student inputs non-integer numbers or inputs values that cannot be calculated, the student will get an error message “Invalid input. This is not correct! Try again”

The code above includes:

Calculating the average scores

And showing the results

Down here I created a function for “Quit” button Once a student is done calculating their average they can click on the Quit button.

def quit_app():
    root.quit()

I love that I could customize the appearance of the input "boxes" to my liking for example the width, font size and I could make it pretty, however, I wanted my calculator to be as basic as possible and serve one purpose only,

# inputting the test results
result1_label = tk.Label(root, text="Enter the score for test 1:")
result2_label = tk.Label(root, text="Enter the score for test 2:")
result3_label = tk.Label(root, text="Enter the score for test 3:")


result1_entry = tk.Entry(root, width=10)
result2_entry = tk.Entry(root, width=10)
result3_entry = tk.Entry(root, width=10)

# the average button
calculate_button = tk.Button(root, text="Average", command=calculate_average)

# The quit button
quit_button = tk.Button(root, text="Quit", command=quit_app)

# label for displaying results
result_label = tk.Label(root, text="", font=("Arial", 12))

This code down here allows me to give my calculator a name:

root = tk.Tk()
root.title("Students Average Test Calculator")

This is how the code looks like step by step in case you might want to code with:

import tkinter as tk

# creating a function that respond when clicked
def calculate_average():
    try:
        # test results + convert to float
        result1_score = float(result1_entry.get())
        result2_score = float(result2_entry.get())
        result3_score = float(result3_entry.get())

        # Calculate the average
        average = (result1_score + result2_score + result3_score) / 3

        # show average results
        result_label.config(text=f"Your Average Score is: {average:.2f}")
    except ValueError:
        result_label.config(text="Invalid input. This is not correct! Try again.")

# declaring function for the quit button
def quit_app():
    root.quit()

# Create the main window
root = tk.Tk()
root.title("Students Average Test Calculator")

# inputting the test results
result1_label = tk.Label(root, text="Enter the score for test 1:")
result2_label = tk.Label(root, text="Enter the score for test 2:")
result3_label = tk.Label(root, text="Enter the score for test 3:")


result1_entry = tk.Entry(root, width=10)
result2_entry = tk.Entry(root, width=10)
result3_entry = tk.Entry(root, width=10)

# the average button
calculate_button = tk.Button(root, text="Average", command=calculate_average)

# The quit button
quit_button = tk.Button(root, text="Quit", command=quit_app)

# label for displaying results
result_label = tk.Label(root, text="", font=("Arial", 12))


# Arrange the grid
result1_label.grid(row=0, column=0, padx=10, pady=5)
result1_entry.grid(row=0, column=1, padx=10, pady=5)
result2_label.grid(row=1, column=0, padx=10, pady=5)
result2_entry.grid(row=1, column=1, padx=10, pady=5)
result3_label.grid(row=2, column=0, padx=10, pady=5)
result3_entry.grid(row=2, column=1, padx=10, pady=5)
calculate_button.grid(row=3, column=0, padx=10, pady=10)
quit_button.grid(row=3, column=1, padx=10, pady=10)
result_label.grid(row=4, column=0, columnspan=2)

#Tkinter main loop
root.mainloop()

Tada! This is what the App looks like! It works as intended and I am really happy with it. I will make a few changes and make it a little colorful but this is a replica of what I was asked to do in my assignment.

You can add error handling, improve the user interface, or experiment with different layouts, colors, and fonts to give it your personal touch.

Before I go, I want to share my Student Average Calculator App with you. You can find the source code on my GitHub repository here. Feel free to use it, modify it, and learn from it. I'm eager to see what you create with it!