DEV Community

Mate Technologies
Mate Technologies

Posted on

Build a Student Grade Calculator with Python Tkinter

In this tutorial, we’ll create a Student Grade Calculator GUI using Python’s Tkinter library. By the end, you’ll have a sleek, interactive app that calculates student grades and keeps a history of entries.

Step 1: Import Tkinter and Configure Theme

First, we need to import Tkinter and define some theme colors to make the app visually appealing.

import tkinter as tk
from tkinter import messagebox

# =========================
# THEME COLORS
# =========================
APP_BG = "#121212"       # Main background
PANEL_BG = "#1F1F1F"     # Panels
BTN_BG = "#2C2C2C"       # Button background
BTN_HOVER = "#3A3A3A"    # Button hover color
BTN_ACTIVE = "#FF6F61"   # Button pressed color
ACCENT = "#FF6F61"       # Accent color for highlights
TEXT_CLR = "#E0E0E0"     # Text color
SUBTEXT_CLR = "#AAAAAA"  # Subtext color
INPUT_BG = "#333333"     # Input field background
INPUT_FG = "#FFFFFF"     # Input field text color
Enter fullscreen mode Exit fullscreen mode

Explanation:
We’re setting up constants for colors to make it easier to maintain a consistent look throughout the app.

Step 2: Create the Main App Class

We’ll wrap our app in a class called StudentGradeApp. This keeps everything organized.

class StudentGradeApp:
    def __init__(self, root):
        self.root = root
        root.title("MateTools – Student Grade Calculator")
        root.geometry("1080x740")   # Window size
        root.configure(bg=APP_BG)
        root.resizable(False, False)
Enter fullscreen mode Exit fullscreen mode

Explanation:

root is the main Tkinter window.

geometry sets the window size.

resizable(False, False) prevents resizing, keeping our layout consistent.

Step 3: Build the Left Panel (Inputs & Actions)

The left panel will contain score inputs and buttons.

# LEFT PANEL
left = tk.Frame(root, bg=PANEL_BG, width=420)
left.pack(side="left", fill="y")

# Header
header = tk.Frame(left, bg=PANEL_BG)
header.pack(fill="x", padx=16, pady=(18, 10))

tk.Label(
    header,
    text="MateTools",
    bg=PANEL_BG,
    fg=ACCENT,
    font=("Segoe UI", 20, "bold")
).pack(side="left")

# App description
tk.Label(
    left,
    text="Student Grade Calculator",
    bg=PANEL_BG,
    fg=TEXT_CLR,
    font=("Segoe UI", 14, "bold")
).pack(anchor="w", padx=16, pady=(0, 2))
Enter fullscreen mode Exit fullscreen mode

Explanation:

We create a frame on the left for inputs and buttons.

Labels give a title and description.

pack(anchor="w") aligns elements to the left.

Step 4: Add Score Entry Fields

We’ll allow users to enter up to 5 scores.

self.scores_entries = []
scores_frame = tk.Frame(left, bg=PANEL_BG)
scores_frame.pack(fill="x", padx=16, pady=(0, 16))

for i in range(5):
    tk.Label(
        scores_frame,
        text=f"Score {i+1}:",
        bg=PANEL_BG,
        fg=SUBTEXT_CLR,
        font=("Segoe UI", 10, "bold")
    ).pack(anchor="w", pady=(2, 0))
    entry = tk.Entry(scores_frame, bg=INPUT_BG, fg=INPUT_FG, font=("Segoe UI", 12))
    entry.pack(fill="x", pady=(0, 5))
    self.scores_entries.append(entry)
Enter fullscreen mode Exit fullscreen mode

Explanation:

We loop 5 times to create 5 input fields.

self.scores_entries keeps references to each input so we can read values later.

Step 5: Add Action Buttons

Now we’ll create Calculate, Clear, and About buttons.

btn_frame = tk.Frame(left, bg=PANEL_BG)
btn_frame.pack(fill="x", padx=16, pady=16)

def make_btn(text, cmd, color=BTN_BG):
    btn = tk.Button(
        btn_frame,
        text=text,
        command=cmd,
        bg=color,
        fg="white",
        font=("Segoe UI", 11, "bold"),
        relief="flat",
        height=2,
        width=20
    )
    # Hover and click effects
    btn.bind("<Enter>", lambda e, b=btn: b.config(bg=BTN_HOVER))
    btn.bind("<Leave>", lambda e, b=btn, c=color: b.config(bg=c))
    btn.bind("<ButtonPress-1>", lambda e, b=btn: b.config(bg=BTN_ACTIVE))
    btn.bind("<ButtonRelease-1>", lambda e, b=btn, c=color: b.config(bg=BTN_HOVER))
    return btn

make_btn("Calculate Grade", self.calculate_grade, ACCENT).pack(side="top", pady=8)
make_btn("Clear", self.clear_fields, BTN_BG).pack(side="top", pady=8)
make_btn("About", self.show_about, BTN_BG).pack(side="top", pady=20)
Enter fullscreen mode Exit fullscreen mode

Explanation:

make_btn is a helper to create uniform buttons with hover and click effects.

Buttons are linked to methods we’ll define later (calculate_grade, clear_fields, show_about).

Step 6: Build the Right Panel (Results & History)

This panel will display the latest grade and a history of calculations.

right = tk.Frame(root, bg=APP_BG)
right.pack(side="right", fill="both", expand=True)

self.result_card = tk.Frame(right, bg=PANEL_BG, bd=2, relief="ridge")
self.result_card.pack(padx=30, pady=20, fill="both", expand=True)

# Result label
tk.Label(
    self.result_card,
    text="Student Grade Calculator",
    bg=PANEL_BG,
    fg=TEXT_CLR,
    font=("Segoe UI", 18, "bold")
).pack(pady=(20, 10))

self.result_label = tk.Label(
    self.result_card,
    text="Grade: --",
    bg=PANEL_BG,
    fg=ACCENT,
    font=("Segoe UI", 18, "bold"),
    width=20
)
self.result_label.pack(anchor="w", pady=(0, 10))
Enter fullscreen mode Exit fullscreen mode

Explanation:

self.result_label shows the latest grade.

Listbox (added next) will show history of previous calculations.

Step 7: Display History of Calculations

self.history_box = tk.Listbox(
    self.result_card,
    bg=INPUT_BG,
    fg=INPUT_FG,
    font=("Segoe UI", 12),
    height=20,
    selectbackground=ACCENT,
    relief="flat"
)
self.history_box.pack(fill="both", expand=True, padx=10, pady=(0, 10))
self.history = []
Enter fullscreen mode Exit fullscreen mode

Explanation:

Listbox displays the last 25 calculated grades.

self.history is a Python list storing history entries.

Step 8: Define Core Methods

Here’s how to calculate grades, update history, clear fields, and show the About dialog.

def calculate_grade(self):
    try:
        scores = [float(entry.get()) for entry in self.scores_entries if entry.get() != ""]
        if not scores:
            raise ValueError("No scores entered")
        average = sum(scores) / len(scores)

        if average >= 90:
            grade = "A"
        elif average >= 80:
            grade = "B"
        elif average >= 70:
            grade = "C"
        elif average >= 60:
            grade = "D"
        else:
            grade = "F"

        result_text = f"{grade} ({average:.2f}%)"
        self.result_label.config(text=f"Grade: {result_text}")

        entry = f"Scores: {', '.join([str(int(s)) for s in scores])} -> Grade: {result_text}"
        self.history.append(entry)
        self.history = self.history[-25:]  # Keep last 25
        self.update_history()
    except ValueError:
        messagebox.showerror("Error", "Please enter valid numeric scores (0-100)")

def update_history(self):
    self.history_box.delete(0, tk.END)
    for item in self.history:
        self.history_box.insert(tk.END, item)

def clear_fields(self):
    for entry in self.scores_entries:
        entry.delete(0, tk.END)
    self.result_label.config(text="Grade: --")
    self.history = []
    self.update_history()

def show_about(self):
    messagebox.showinfo(
        "About",
        "MateTools – Student Grade Calculator\n\n"
        "• Enter up to 5 scores (0-100)\n"
        "• Calculates average and grade\n"
        "• Tracks last 25 calculated grades\n\n"
        "Built by MateTools"
    )
Enter fullscreen mode Exit fullscreen mode

Explanation:

calculate_grade reads inputs, computes the average, determines the letter grade, and updates the label and history.

clear_fields resets all inputs and history.

show_about shows an information dialog.

Step 9: Run the Application

Finally, we create the Tkinter root window and launch the app.

if __name__ == "__main__":
    root = tk.Tk()
    StudentGradeApp(root)
    root.mainloop()
Enter fullscreen mode Exit fullscreen mode

Explanation:

root.mainloop() starts the Tkinter event loop.

Without it, the window wouldn’t appear.

✅ Congrats! You now have a full-featured Student Grade Calculator GUI.

You can extend this by adding more inputs, custom grading rules, or file export.

Student Grade Calculator

Top comments (0)