How to create a library book borrowing system in Python
Install Tkinter and build user login/registration screen
To build a system to borrow books, you will use Tkinter. Tkinter is the standard GUI library for Python desktop applications. To install it, type the following code in the terminal:
pip install tkinter
Import the required module and define a class, BookBorrowingSystem . Define a constructor for the class and root window, and set the title, size, and background color for the application. Define two lists, books and lend_list , which you will use to store titles of books and books that have been borrowed.
Defines a dictionary, record, that you can use to update the status of the book. Use the setup_gui() method to create a graphical user interface and initialize an empty list of librarians that you will use to store login information.
import tkinter as tk from tkinter import messagebox class BookBorrowingSystem: def __init__(self): self.master = tk.Tk() self.master.title("Book Borrowing System") self.master.geometry("750x600") self.master.config(bg='#708090') self.books = [] self.lend_list = [] self.record = {} self.setup_gui() self.librarians = []
Define a method, setup_gui() . For the signup/login screen, you will create 3 labels named login_label , username_label , and password_label . For each label, specify the parent element you want to place it inside, the text it should display, including the font style and color.
Along with the labels, you need to create 2 input widgets named username_entry and password_entry to receive and store the librarian's credentials. Use the pack manager to organize all these widgets and add appropriate padding for a visual accent.
def setup_gui(self): self.login_label = tk.Label(self.master, text="Book Borrowing System", font=("Helvetica", 24), bg='#708090', fg='white') self.login_label.pack(pady=(30, 10)) self.login_button = tk.Button(self.master, text="Login", command=self.login, font=("Helvetica", 14)) self.login_button.pack(pady=10) # Tương tự, tạo username_label, username_entry, password_label, # password_entry, và nút bấm register
Define a method, login() . Use get() on the input widget to retrieve the credentials value entered by the librarian. Iterate over the list of librarians and check to see if the username and password match the entered data. If true, delete the entered value from start to finish. Remove all created widgets and call book_management_screen() to display the management screen of the borrowing system.
In other cases, the login information is wrong or the librarian is not registered. Show appropriate notifications via Tkinter's notification box widget. In case you want to encrypt the password, install the bcrypt module.
elf.username_entry.get() password = self.password_entry.get() for librarian in self.librarians: if username == librarian[0] and password == librarian[1]: self.username_entry.delete(0, tk.END) self.password_entry.delete(0, tk.END) self.login_label.destroy() # Phá hủy toàn bộ entries, labels, và buttons self.book_management_screen() return messagebox.showerror("Error", "Invalid username or password. Please register if not done already.")
Define a method, register() . Retrieve the credentials value entered by the librarian, add them to the librarian's list, and delete the entries entirely.
def register(self): username = self.username_entry.get() password = self.password_entry.get() self.librarians.append([username, password]) self.username_entry.delete(0, tk.END) self.password_entry.delete(0, tk.END)
Define a method, book_management_screen() . Create 4 labels named add_book_label , return_book_label , remove_book_label , and issue_book_label . Create 4 items and 4 buttons corresponding to these labels, and another button to see a list of all books and their status. Use the package manager to arrange the elements and add a little padding.
def book_management_screen(self): self.add_book_label = tk.Label(self.master, text="Add Book", font=("Helvetica", 18), bg='#708090', fg='white') self.add_book_label.pack(pady=(20, 5)) self.add_book_entry = tk.Entry(self.master, font=("Helvetica", 14)) self.add_book_entry.pack() self.add_book_button = tk.Button(self.master, text="Add Book", command=self.add_book, font=("Helvetica", 14)) self.add_book_button.pack(pady=5) # Lặp lại code tương tự cho return_book, remove_book, issue_book self.view_books_button = tk.Button(self.master, text="View Books", command=self.view_books, font=("Helvetica", 14)) self.view_books_button.pack(pady=10)
Build a function for the book lending system
Define a function, add_book() . Retrieve the content of the input widget and add it to the list. In the record dictionary, add the keyword as the book title and the value as added . Show a success message box indicating that the program has completed adding books. Delete the contents of add_book_entry from beginning to end.
def add_book(self): book = self.add_book_entry.get() self.books.append(book) self.record[book] = "added" messagebox.showinfo("Success", "Book added successfully") self.add_book_entry.delete(0, tk.END)
Define a method, remove_book() . Retrieve the book title and check if it is present in the books list . If exists, remove it and the corresponding records from the dictionary. Once completed, a success message will appear indicating that the program has removed the book. If not, an error message box will appear stating that the book was not found. Remove the remove_book_entry entry completely .
def remove_book(self): book = self.remove_book_entry.get() if book in self.books: self.books.remove(book) if book in self.record: del self.record[book] messagebox.showinfo("Success", "Book removed successfully") else: messagebox.showerror("Error", "Book not found") self.remove_book_entry.delete(0, tk.END)
Define a method, issue_book() . Retrieve the book name and check if it exists in the books list . If it is, append it to the list of books. Update book value is issued . If not, an error message box will appear stating that the book cannot be found. Delete the contents of issue_book_entry() .
def issue_book(self): book = self.issue_book_entry.get() if book in self.books: self.lend_list.append(book) self.books.remove(book) self.record[book] = "issued" messagebox.showinfo("Success", "Book issued successfully") else: messagebox.showerror("Error", "Book not found") self.issue_book_entry.delete(0, tk.END)
Define a return_book() method . Retrieve the title and check if it exists in the lend_list . If so, remove it and append it back to the list of books & update the value in the record as returned. The box shows that the borrower has returned the book.
If the book title already exists in the list and the status of the read record added , an error message box will appear stating that the person cannot return the book because no one has accepted it. Otherwise, display an error message box saying that the book was not found.
def return_book(self): book = self.return_book_entry.get() if book in self.lend_list: self.lend_list.remove(book) self.books.append(book) self.record[book] = "returned" messagebox.showinfo("Success", "Book returned successfully") elif book in self.books and self.record.get(book) == "added": messagebox.showerror("Error", "Book can't be returned. It hasn't been issued.") else: messagebox.showerror("Error", "Book not found.") self.return_book_entry.delete(0, tk.END)
Define a method, view_books( ) . Initialize the message variable as empty. Generates a message that performs string interpolation and displays the title and its status. If the message is blank, the book is not currently available. Show the corresponding result in a message box.
def view_books(self): message = "" for book, status in self.record.items(): message += f"{book}: {status}n" if not message: message = "No book records available." messagebox.showinfo("Books", message)
Create a class instance and run mainloop() Tkinter to listen for events until you close the window. Use __name__ == "__main__" to run this program.
def run(self): self.master.mainloop() if __name__ == "__main__": book_borrowing_system = BookBorrowingSystem() book_borrowing_system.run()
Result of the above example:
Login screen when running the program. Enter the information and click the Register button, the program will add you as a librarian. Entering the same information and pressing Login will take you to the management screen.
When entering the title of the book and clicking Add Book, the program displays a message box that says the book has been successfully added. If the issue, return or remove button is clicked, the program displays the appropriate message dialog while updating its status.
When the View Books button is clicked, the program displays the title of the book along with its status. If the book is removed, the program deletes the name and you cannot view it.
In case you return unreleased books or delete published books, the program will display an error message.
Above is how to program a library management system in Python. Hope the article is useful to you.
You should read it
- More than 100 Python exercises have solutions (sample code)
- 5 choose the best Python IDE for you
- How to set up Python to program on WSL
- For in Python loop
- Programming Python on Android device
- What is Python? Why choose Python?
- Python data type: string, number, list, tuple, set and dictionary
- Manage files and folders in Python
- Bookmark 5 best Python programming learning websites
- Python online editor
- Multiple choice quiz about Python - Part 3
- Why should you learn Python programming language?
Maybe you are interested
Basic steps to build self-confidence in children
How to take care of yourself when you are sick
How to try to crack a password yourself to test its strength
Ways to Transform Yourself into a Better Version in the New Year
How to effectively 'market' yourself in the job market
Why not use AI to edit selfies and portraits?