Student Data Entry Application with Tkinter and CSV

Student data Entry application

This Python script is a student information management tool built with Tkinter for the graphical interface and CSV for data storage. It allows users to input student details such as name, class, mark, and gender via an interactive form. The data is saved in a CSV file located in the same directory as the script. The application also displays the 10 most recent student records in a grid format below the form, providing an efficient way to manage student information without needing a database.

1. CSV Creation and Setup

file_name = os.path.dirname(os.path.abspath(__file__)) + '/student.csv'
if not os.path.exists(file_name):
    with open(file_name, mode='w', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(["id", "name", "class", "mark", "gender"])
Explanation: This block creates the CSV file (`student.csv`) in the script's directory if it doesn’t already exist. The headers: **id, name, class, mark, gender** are written to the file.

2. Adding Student Data to CSV

def add_student():
    name = name_var.get()
    student_class = class_var.get()
    mark = mark_var.get()
    gender = gender_var.get()

    if name and student_class and mark and gender:
        with open(file_name, mode='a+', newline='') as file:
            writer = csv.writer(file)
            reader = csv.reader(file)
            rows = list(reader)
            new_id = len(rows)
            writer.writerow([new_id, name, student_class, mark, gender])
        display_recent_entries()
        clear_form()
    else:
        messagebox.showerror("Input Error", "All fields are required")
Explanation: This function retrieves user input from the form (name, class, mark, gender) and appends it to the CSV file. It auto-increments the ID based on the number of rows in the file.

3. Displaying Recent Entries

def display_recent_entries():
    for widget in record_frame.winfo_children():
        widget.destroy()

    tk.Label(record_frame, text="Name", font=("Arial", 10, "bold")).grid(row=0, column=0)
    tk.Label(record_frame, text="Class", font=("Arial", 10, "bold")).grid(row=0, column=1)
    tk.Label(record_frame, text="Mark", font=("Arial", 10, "bold")).grid(row=0, column=2)
    tk.Label(record_frame, text="Gender", font=("Arial", 10, "bold")).grid(row=0, column=3)

    if os.path.exists(file_name):
        with open(file_name, mode='r') as file:
            reader = csv.reader(file)
            rows = list(reader)[1:]
            recent_rows = rows[-10:]
            for i, row in enumerate(recent_rows):
                tk.Label(record_frame, text=row[1]).grid(row=i + 1, column=0)
                tk.Label(record_frame, text=row[2]).grid(row=i + 1, column=1)
                tk.Label(record_frame, text=row[3]).grid(row=i + 1, column=2)
                tk.Label(record_frame, text=row[4]).grid(row=i + 1, column=3)
Explanation: This function displays the 10 most recent entries in a grid format within the Tkinter window. It reads the CSV, extracts the last 10 records, and presents them with columns: **Name, Class, Mark, Gender**.

4. Clearing Form Fields

def clear_form():
    name_var.set("")
    class_var.set("")
    mark_var.set("")
    gender_var.set(None)
Explanation: This function resets the input fields to empty after a student record is successfully added.

5. Tkinter Layout and Setup

my_w = tk.Tk()
my_w.title("Student Entry Form")
my_w.geometry("500x500")
Explanation: This block sets up the main Tkinter window with a title and window dimensions.

6. Input Fields

name_var = tk.StringVar()
class_var = tk.StringVar()
mark_var = tk.StringVar()
gender_var = tk.StringVar(value=None)
Explanation: These variables hold the user’s form input. They store values for **Name**, **Class**, **Mark**, and **Gender**.

7. Submit Button

tk.Button(my_w, text="Add Student", command=add_student).grid(row=2, column=0, columnspan=6, pady=20)
Explanation: This button triggers the `add_student()` function when clicked, saving the student’s details in the CSV file.

8. Display Records Frame

record_frame = tk.Frame(my_w)
record_frame.grid(row=3, column=0, columnspan=6, pady=10)
Explanation: This frame is used to display the 10 most recent entries in the CSV file.

9. Initial Display Setup

display_recent_entries()
gender_var.set(None)
Explanation: This part calls the `display_recent_entries()` function when the application starts to display existing records from the CSV. It also clears the gender field initially.
import tkinter as tk
from tkinter import ttk
import csv
import os
from tkinter import messagebox

# Ensure CSV is created in the current directory
#file_name = os.path.join(os.getcwd(), 'student.csv')
file_name=os.path.dirname(os.path.abspath(__file__))+'/student.csv'
#print(os.getcwd())
#print(os.path.dirname(os.path.abspath(__file__)))
#print(file_name)
if not os.path.exists(file_name):
    with open(file_name, mode='w', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(["id", "name", "class", "mark", "gender"])

# Function to add student details to CSV
def add_student():
    name = name_var.get()
    student_class = class_var.get()
    mark = mark_var.get()
    gender = gender_var.get()

    if name and student_class and mark and gender:
        with open(file_name, mode='a+', newline='') as file:
            writer = csv.writer(file)
            reader = csv.reader(file)
            rows = list(reader)
            new_id = len(rows)
            writer.writerow([new_id, name, student_class, mark, gender])
        display_recent_entries()
        clear_form()
    else:
        messagebox.showerror("Input Error", "All fields are required")

# Display the 10 most recent entries
def display_recent_entries():
    for widget in record_frame.winfo_children():
        widget.destroy()

    tk.Label(record_frame, text="Name", font=("Arial", 10, "bold")).grid(row=0, column=0)
    tk.Label(record_frame, text="Class", font=("Arial", 10, "bold")).grid(row=0, column=1)
    tk.Label(record_frame, text="Mark", font=("Arial", 10, "bold")).grid(row=0, column=2)
    tk.Label(record_frame, text="Gender", font=("Arial", 10, "bold")).grid(row=0, column=3)

    if os.path.exists(file_name):
        with open(file_name, mode='r') as file:
            reader = csv.reader(file)
            rows = list(reader)[1:]
            recent_rows = rows[-10:]
            for i, row in enumerate(recent_rows):
                tk.Label(record_frame, text=row[1]).grid(row=i + 1, column=0)
                tk.Label(record_frame, text=row[2]).grid(row=i + 1, column=1)
                tk.Label(record_frame, text=row[3]).grid(row=i + 1, column=2)
                tk.Label(record_frame, text=row[4]).grid(row=i + 1, column=3)

# Clear form fields after adding a student
def clear_form():
    name_var.set("")
    class_var.set("")
    mark_var.set("")
    gender_var.set(None)

# Tkinter window setup
my_w = tk.Tk()
my_w.title("Student Entry Form")
my_w.geometry("500x500")

# Form variables
name_var = tk.StringVar()
class_var = tk.StringVar()
mark_var = tk.StringVar()
gender_var = tk.StringVar(value=None)

# Entry fields in one line using grid layout
tk.Label(my_w, text="Name").grid(row=0, column=0, padx=5, pady=10)
tk.Entry(my_w, textvariable=name_var).grid(row=0, column=1, padx=5, pady=10)

tk.Label(my_w, text="Class").grid(row=0, column=2, padx=5, pady=10)
class_combobox = ttk.Combobox(my_w, textvariable=class_var,width=10)
class_combobox['values'] = ("Three", "Four", "Five", "Six")
class_combobox.grid(row=0, column=3, padx=5, pady=10)

tk.Label(my_w, text="Mark").grid(row=0, column=4, padx=5, pady=10)
tk.Entry(my_w, textvariable=mark_var,width=5).grid(row=0, column=5, padx=5, pady=10)

# Gender radio buttons
tk.Label(my_w, text="Gender").grid(row=1, column=0, padx=5, pady=10)
tk.Radiobutton(my_w, text="Male", variable=gender_var, value="Male").grid(row=1, column=1, padx=5, pady=10)
tk.Radiobutton(my_w, text="Female", variable=gender_var, value="Female").grid(row=1, column=2, padx=5, pady=10)
tk.Radiobutton(my_w, text="Others", variable=gender_var, value="Others").grid(row=1, column=3, padx=5, pady=10)

# Submit button
tk.Button(my_w, text="Add Student", command=add_student).grid(row=2, column=0, columnspan=6, pady=20)
str1=tk.StringVar(value=file_name)
l1=tk.Label(my_w,width=30,textvariable=str1)
l1.grid(row=3,column=0,columnspan=6)
# Frame to display recent records
record_frame = tk.Frame(my_w)
record_frame.grid(row=4, column=0, columnspan=6, pady=10)



# Initially display recent entries
display_recent_entries()
gender_var.set(None)
my_w.mainloop()

Browse and save CSV file in local system

Browse and save csv file

Here is the modified code with an additional button that allows the user to browse and save the CSV file to any location on their system. The selected file path is dynamically updated, and student records are saved to this location.
import tkinter as tk
from tkinter import ttk
import csv
import os
from tkinter import messagebox, filedialog

# Default file location
file_name = os.path.dirname(os.path.abspath(__file__)) + '/student.csv'

# Ensure the CSV file exists at the default location
if not os.path.exists(file_name):
    with open(file_name, mode='w', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(["id", "name", "class", "mark", "gender"])

# Function to change the file save location
def browse_file():
    global file_name
    file_path = filedialog.asksaveasfilename(
        defaultextension=".csv",
        filetypes=[("CSV files", "*.csv"), ("All files", "*.*")]
    )
    if file_path:
        file_name = file_path
        str1.set(file_name)  # Update the label to display the new file path
        if not os.path.exists(file_name):
            with open(file_name, mode='w', newline='') as file:
                writer = csv.writer(file)
                writer.writerow(["id", "name", "class", "mark", "gender"])

# Function to add student details to CSV
def add_student():
    name = name_var.get()
    student_class = class_var.get()
    mark = mark_var.get()
    gender = gender_var.get()

    if name and student_class and mark and gender:
        with open(file_name, mode='a+', newline='') as file:
            writer = csv.writer(file)
            reader = csv.reader(file)
            rows = list(reader)
            new_id = len(rows)
            writer.writerow([new_id, name, student_class, mark, gender])
        display_recent_entries()
        clear_form()
    else:
        messagebox.showerror("Input Error", "All fields are required")

# Display the 10 most recent entries
def display_recent_entries():
    for widget in record_frame.winfo_children():
        widget.destroy()

    tk.Label(record_frame, text="Name", font=("Arial", 10, "bold")).grid(row=0, column=0)
    tk.Label(record_frame, text="Class", font=("Arial", 10, "bold")).grid(row=0, column=1)
    tk.Label(record_frame, text="Mark", font=("Arial", 10, "bold")).grid(row=0, column=2)
    tk.Label(record_frame, text="Gender", font=("Arial", 10, "bold")).grid(row=0, column=3)

    if os.path.exists(file_name):
        with open(file_name, mode='r') as file:
            reader = csv.reader(file)
            rows = list(reader)[1:]
            recent_rows = rows[-10:]
            for i, row in enumerate(recent_rows):
                tk.Label(record_frame, text=row[1]).grid(row=i + 1, column=0)
                tk.Label(record_frame, text=row[2]).grid(row=i + 1, column=1)
                tk.Label(record_frame, text=row[3]).grid(row=i + 1, column=2)
                tk.Label(record_frame, text=row[4]).grid(row=i + 1, column=3)

# Clear form fields after adding a student
def clear_form():
    name_var.set("")
    class_var.set("")
    mark_var.set("")
    gender_var.set(None)

# Tkinter window setup
my_w = tk.Tk()
my_w.title("Student Entry Form")
my_w.geometry("600x500")

# Form variables
name_var = tk.StringVar()
class_var = tk.StringVar()
mark_var = tk.StringVar()
gender_var = tk.StringVar(value=None)

# Entry fields in one line using grid layout
tk.Label(my_w, text="Name").grid(row=0, column=0, padx=5, pady=10)
tk.Entry(my_w, textvariable=name_var).grid(row=0, column=1, padx=5, pady=10)

tk.Label(my_w, text="Class").grid(row=0, column=2, padx=5, pady=10)
class_combobox = ttk.Combobox(my_w, textvariable=class_var, width=10)
class_combobox['values'] = ("Three", "Four", "Five", "Six")
class_combobox.grid(row=0, column=3, padx=5, pady=10)

tk.Label(my_w, text="Mark").grid(row=0, column=4, padx=5, pady=10)
tk.Entry(my_w, textvariable=mark_var, width=5).grid(row=0, column=5, padx=5, pady=10)

# Gender radio buttons
tk.Label(my_w, text="Gender").grid(row=1, column=0, padx=5, pady=10)
tk.Radiobutton(my_w, text="Male", variable=gender_var, value="Male").grid(row=1, column=1, padx=5, pady=10)
tk.Radiobutton(my_w, text="Female", variable=gender_var, value="Female").grid(row=1, column=2, padx=5, pady=10)
tk.Radiobutton(my_w, text="Others", variable=gender_var, value="Others").grid(row=1, column=3, padx=5, pady=10)

# Submit button
tk.Button(my_w, text="Add Student", command=add_student).grid(row=2, column=0, columnspan=6, pady=10)

# Browse button to set save location
tk.Button(my_w, text="Set Save Location", command=browse_file).grid(row=3, column=0, columnspan=6, pady=10)

# Display file location
str1 = tk.StringVar(value=file_name)
tk.Label(my_w, textvariable=str1, width=50, fg="blue").grid(row=4, column=0, columnspan=6, pady=10)

# Frame to display recent records
record_frame = tk.Frame(my_w)
record_frame.grid(row=5, column=0, columnspan=6, pady=10)

# Initially display recent entries
display_recent_entries()
gender_var.set(None)
my_w.mainloop()

Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer