In this article, we’ll create a CRUD (Create, Read, Update, Delete) application in Python using Object-Oriented Programming (OOP) principles. We’ll also incorporate a graphical user interface (GUI) using the tkinter
library. This application will manage a simple database of items, such as a list of books. We’ll cover the following steps:
- Application Diagram
- Setting Up the Project Structure
- Creating the Main Application File
- Implementing the Data Model
- Building the GUI
- Integrating CRUD Operations
- Running the Application
1. Application Diagram
Here’s a diagram of the application structure:
Main Application
|
|-- Data Model (Book class)
|
|-- GUI (Tkinter)
|
|-- Add Book
|-- View Books
|-- Update Book
|-- Delete Book
2. Setting Up the Project Structure
Create a project directory with the following structure:
2. Setting Up the Project Structure
Create a project directory with the following structure:
3. Creating the Main Application File
The main.py
file will be the entry point of our application.
# main.py
# Import the BookApp class from gui.py
from gui import BookApp
# Check if the script is run directly (not imported)
if __name__ == "__main__":
# Create an instance of BookApp
app = BookApp()
# Run the application
app.run()
Entry Point (
main.py
):- The
main.py
file serves as the entry point of the application. It imports theBookApp
class fromgui.py
and runs the application.
- The
4. Implementing the Data Model
Create a book.py
file to define the Book
class, which will handle the data model.
# book.py
# Define the Book class to represent a book with attributes title, author, year, and isbn
class Book:
# Class variable to store all books
books = []
# Constructor to initialize a Book object
def __init__(self, title, author, year, isbn):
self.title = title
self.author = author
self.year = year
self.isbn = isbn
# Class method to add a book to the list
@classmethod
def add_book(cls, book):
cls.books.append(book)
# Class method to get all books
@classmethod
def get_books(cls):
return cls.books
# Class method to update a book at a specific index
@classmethod
def update_book(cls, index, new_book):
if 0 <= index < len(cls.books):
cls.books[index] = new_book
# Class method to delete a book at a specific index
@classmethod
def delete_book(cls, index):
if 0 <= index < len(cls.books):
cls.books.pop(index)
Data Model (
book.py
):- The
Book
class inbook.py
defines the structure and behavior of book objects. - It includes class methods to add, retrieve, update, and delete books from a list.
- The
Explanation of book.py
- Book Class: Represents a book with attributes
title
,author
,year
, andisbn
. - Class Variable:
books
stores all book instances. - Constructor (
__init__
): Initializes a new book instance with provided details. - Class Methods: These methods operate on the
books
list:add_book
: Adds a new book to the list.get_books
: Returns the list of all books.update_book
: Updates a book at the given index.delete_book
: Deletes a book at the given index.
5. Building the GUI
Create a gui.py
file to build the GUI using tkinter
.
# gui.py
import tkinter as tk
from tkinter import messagebox
from book import Book
# Define the BookApp class to manage the GUI
class BookApp:
def __init__(self):
# Initialize the main window
self.root = tk.Tk()
self.root.title("Book Manager")
# Create the GUI components
self.create_widgets()
def create_widgets(self):
# Create and place the title label and entry
self.title_label = tk.Label(self.root, text="Title")
self.title_label.grid(row=0, column=0)
self.title_entry = tk.Entry(self.root)
self.title_entry.grid(row=0, column=1)
# Create and place the author label and entry
self.author_label = tk.Label(self.root, text="Author")
self.author_label.grid(row=1, column=0)
self.author_entry = tk.Entry(self.root)
self.author_entry.grid(row=1, column=1)
# Create and place the year label and entry
self.year_label = tk.Label(self.root, text="Year")
self.year_label.grid(row=2, column=0)
self.year_entry = tk.Entry(self.root)
self.year_entry.grid(row=2, column=1)
# Create and place the ISBN label and entry
self.isbn_label = tk.Label(self.root, text="ISBN")
self.isbn_label.grid(row=3, column=0)
self.isbn_entry = tk.Entry(self.root)
self.isbn_entry.grid(row=3, column=1)
# Create and place the Add Book button
self.add_button = tk.Button(self.root, text="Add Book", command=self.add_book)
self.add_button.grid(row=4, column=0)
# Create and place the View Books button
self.view_button = tk.Button(self.root, text="View Books", command=self.view_books)
self.view_button.grid(row=4, column=1)
# Create and place the Update Book button
self.update_button = tk.Button(self.root, text="Update Book", command=self.update_book)
self.update_button.grid(row=5, column=0)
# Create and place the Delete Book button
self.delete_button = tk.Button(self.root, text="Delete Book", command=self.delete_book)
self.delete_button.grid(row=5, column=1)
# Create and place the listbox to display books
self.book_list = tk.Listbox(self.root, height=10, width=50)
self.book_list.grid(row=6, column=0, columnspan=2)
self.book_list.bind('<<ListboxSelect>>', self.on_select)
# Initialize selected book index
self.selected_index = None
def add_book(self):
# Get input from the entry fields
title = self.title_entry.get()
author = self.author_entry.get()
year = self.year_entry.get()
isbn = self.isbn_entry.get()
# Validate input and add book to the list
if title and author and year and isbn:
book = Book(title, author, year, isbn)
Book.add_book(book)
messagebox.showinfo("Success", "Book added successfully!")
self.clear_entries()
else:
messagebox.showwarning("Input Error", "Please fill all fields")
def view_books(self):
# Clear the listbox
self.book_list.delete(0, tk.END)
# Insert all books into the listbox
for book in Book.get_books():
self.book_list.insert(tk.END, f"{book.title} by {book.author} ({book.year}) [ISBN: {book.isbn}]")
def update_book(self):
# Check if a book is selected and get input from the entry fields
if self.selected_index is not None:
title = self.title_entry.get()
author = self.author_entry.get()
year = self.year_entry.get()
isbn = self.isbn_entry.get()
# Validate input and update the selected book
if title and author and year and isbn:
updated_book = Book(title, author, year, isbn)
Book.update_book(self.selected_index, updated_book)
messagebox.showinfo("Success", "Book updated successfully!")
self.view_books()
self.clear_entries()
else:
messagebox.showwarning("Input Error", "Please fill all fields")
def delete_book(self):
# Check if a book is selected and delete it
if self.selected_index is not None:
Book.delete_book(self.selected_index)
messagebox.showinfo("Success", "Book deleted successfully!")
self.view_books()
self.clear_entries()
def on_select(self, event):
# Handle listbox selection and populate entry fields with selected book data
try:
index = self.book_list.curselection()[0]
self.selected_index = index
selected_book = Book.get_books()[index]
self.title_entry.delete(0, tk.END)
self.title_entry.insert(tk.END, selected_book.title)
self.author_entry.delete(0, tk.END)
self.author_entry.insert(tk.END, selected_book.author)
self.year_entry.delete(0, tk.END)
self.year_entry.insert(tk.END, selected_book.year)
self.isbn_entry.delete(0, tk.END)
self.isbn_entry.insert(tk.END, selected_book.isbn)
except IndexError:
self.selected_index = None
def clear_entries(self):
# Clear all entry fields
self.title_entry.delete(0, tk.END)
self.author_entry.delete(0, tk.END)
self.year_entry.delete(0, tk.END)
self.isbn_entry.delete(0, tk.END)
def run(self):
# Start the Tkinter main loop
self.root.mainloop()
GUI (
gui.py
):- The
BookApp
class creates the GUI usingtkinter
. - The
create_widgets
method sets up the input fields, buttons, and listbox for user interaction. - The
add_book
,view_books
,update_book
, anddelete_book
methods handle the respective CRUD operations. - The
on_select
method handles listbox selections, populating the input fields with the selected book’s data. - The
clear_entries
method clears all input fields. - The
run
method starts the Tkinter main loop, running the application.
- The
Explanation of gui.py
- BookApp Class: Manages the GUI components and user interactions.
- Initialization (
__init__
): Sets up the main window and initializes the GUI components. - Create Widgets (
create_widgets
): Defines the input fields, buttons, and listbox, and places them in the grid layout. - CRUD Methods: These methods handle adding, viewing, updating, and deleting books, interacting with the
Book
class:add_book
: Collects input from the fields, creates aBook
object, and adds it to the list.view_books
: Displays all books in the listbox.update_book
: Updates the selected book with new data.delete_book
: Deletes the selected book.on_select
: Handles listbox selection to fill input fields with the selected book’s data.clear_entries
: Clears all input fields.
- Run Method (
run
): Starts the Tkinter main loop, which runs the application
6. Integrating CRUD Operations
The BookApp
class integrates the CRUD operations using the Book
class methods and manages the GUI components.
7. Running the Application
To run the application, execute the main.py
file:
python main.py
This will open the Book Manager application window, where you can add, view, update, and delete books.
Welcome to DevTechTutor.com, your ultimate resource for mastering web development and technology! Whether you're a beginner eager to dive into coding or an experienced developer looking to sharpen your skills, DevTechTutor.com is here to guide you every step of the way. Our mission is to make learning web development accessible, engaging, and effective.