Source Code
Source Code
● INTRODUCTION
● SOURCE CODE
● OUTPUT
● FUNCTIONS USED
● BIBLIOGRAPHY
HARDWARE AND SOFTWARE REQUIREMENT
OS - Windows 10 professional 64bit, OS build
19042.1288
Language - English
System manufacturer - Gigabyte Technology Co., Ltd
Processor - Intel(R) Core™ i5-3470 CPU @ 3.20GHz,
3601 MHz, 4 core(s)
Memory - 2048 MB RAM
DirectX version - Direct XII
DISPLAY DEVICE
Device name - DESKTOP-2DARPOG
Manufacturer - Gigabyte Technology Co., Ltd
Chip type - Intel HD Graphics Family
DAC type - Internal Current display mode - 1366 x 768
Monitor - Generic PnP Monitor
SOFTWARE
Python version - 3.9.5 MySQL - 8.0
import tkinter as tk
from tkinter import messagebox
from PIL import Image, ImageTk
import mysql.connector
import time
from datetime import datetime
from datetime import date
from tkinter import ttk
from prettytable import PrettyTable
from datetime import datetime, timedelta
import math
from datetime import datetime
# Global variables for database connection
con = None
mycur = None
user_type_var = None
canvas=None
def database():
global con, mycur
try:
con = mysql.connector.connect(
host="localhost",
user="root",
password="welcome123",
database="admin"
)
mycur = con.cursor() # Initialize cursor
print("Connection and cursor initialized")
except mysql.connector.Error as err:
print(f"Error: {err}")
def close_connection():
global mycur, con
if mycur:
mycur.close()
if con:
con.close()
def main():
database() # Initialize database connection
mainframe() # Initialize the main frame
def mainframe():
global bg_image, overlay, user_entry, password_entry, user_type_var # Declare as global to
use them in show_dashboard
bg_image = Image.open(r"C:\Users\Admin\Downloads\Designer.png").resize((900, 500))
bg_image = ImageTk.PhotoImage(bg_image)
def show_dashboard():
global user_type_var
global user_entry, password_entry ,canvas,bg_image
for widget in root.winfo_children():
widget.destroy() # Clear existing widgets
bg_image = Image.open(r"C:\Users\Admin\Downloads\Designer.png").resize((900, 500))
bg_image = ImageTk.PhotoImage(bg_image)
canvas = tk.Canvas(root, height=500, width=900)
canvas.pack()
canvas.create_image(0, 0, anchor=tk.NW, image=bg_image)
# User ID
user_label = tk.Label(root, text='User ID', bg='black', font=('Arial', 12, 'bold'), fg='white')
user_label.place(x=200, y=100)
# Login Button
login_button = tk.Button(root, text='Login', fg='black', bg='yellow', width=10,
font=('Arial', 12, 'bold'), activebackground='black',
activeforeground='yellow', command=process_login, bd=3, relief='flat',
cursor='hand2')
login_button.place(x=220, y=250)
# Clear Button
clear_button = tk.Button(root, text='Clear', fg='black', bg='yellow', width=10,
font=('Arial', 12, 'bold'), activebackground='black',
activeforeground='yellow', bd=3, relief='flat', cursor='hand2',
command=clear_entries)
clear_button.place(x=360, y=250)
user_type_var = tk.StringVar()
user_type_label = tk.Label(canvas, text='User Type', bg='black', font=('Arial', 12, 'bold'),
fg='white')
user_type_label.place(x=180, y=200)
def login():
global user_type_var
user_type_var = tk.StringVar(value="student")
def signup():
global user_type_var
new_window = tk.Toplevel(root)
new_window.title("Sign Up")
new_window.geometry("400x300")
new_window.configure(bg='#f0f0f0')
user_type_var = tk.StringVar(value="student")
tk.Label(new_window, text="Select User Type", font=('Arial', 14, 'bold'), bg='#f0f0f0',
fg='#333').pack(pady=20)
def submit_student_form():
student_id = stud_id.get()
student_name = name.get()
student_class = stud_class.get()
student_section = section.get()
user = user_id.get()
passwd = password.get()
if not (student_id and student_name and student_class and student_section and user and
passwd):
messagebox.showerror("Input Error", "All fields are required.")
return
database()
try:
mycur.execute("INSERT INTO userlogin (UserID, Password, Type) VALUES (%s, %s,
'student')", (user, passwd))
mycur.execute("INSERT INTO student (stud_id, name, class, sec) VALUES (%s, %s, %s,
%s)",
(student_id, student_name, student_class, student_section))
con.commit()
messagebox.showinfo("Success", "Student registered successfully!")
except mysql.connector.Error as err:
messagebox.showerror("Database Error", f"Error: {err}")
finally:
mycur.close()
con.close()
def open_teacher_form():
global teacher_id, name, department, user_id, password
new_window = tk.Toplevel(root)
new_window.title("Teacher Sign Up")
new_window.geometry("350x500")
new_window.configure(bg='#e7f3fe')
def submit_teacher_form():
t_id = teacher_id.get()
t_name = teacher_name.get()
t_department = department.get()
user = user_id.get()
passwd = password.get()
if not (t_id and t_name and t_department and user and passwd):
messagebox.showerror("Input Error", "All fields are required.")
return
database()
try:
mycur.execute("INSERT INTO userlogin (UserID, Password, Type) VALUES (%s, %s,
'teacher')", (user, passwd))
mycur.execute("INSERT INTO teacher (teacher_id, name, department) VALUES (%s, %s,
%s)",
(t_id, t_name, t_department))
con.commit()
messagebox.showinfo("Success", "Teacher registered successfully!")
except mysql.connector.Error as err:
messagebox.showerror("Database Error", f"Error: {err}")
finally:
mycur.close()
con.close()
def forgot_password():
new_window = tk.Toplevel(root) # Use root as master
new_window.title("Forgot Password")
new_window.geometry("450x400")
new_window.configure(bg='#f0e68c') # Set background color
header = tk.Label(new_window, text="Forgot Password", font=('Arial', 16, 'bold'),
bg='#f0e68c', fg='navy')
header.pack(pady=10)
try:
cursor.execute("SELECT * FROM userlogin WHERE UserID = %s", (user_id,))
result = cursor.fetchone()
if result:
cursor.execute("UPDATE userlogin SET Password = %s WHERE UserID = %s",
(new_password, user_id))
conn.commit()
messagebox.showinfo("Success", "Password reset successfully.")
else:
messagebox.showerror("Error", "User ID not found.")
finally:
cursor.close()
conn.close()
def clear_entries():
global user_entry, password_entry
user_entry.delete(0, tk.END)
password_entry.delete(0, tk.END)
def process_login():
global login_window, entry_user_id, entry_password, user_type_var
user_type = user_type_var.get()
user_id = user_entry.get()
password = password_entry.get()
if user_type_var is not None:
user_type = user_type_var.get()
else:
messagebox.showerror("Error", "User type is not defined")
return
try:
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="welcome123",
database="admin"
)
cursor = mydb.cursor()
if user_type == "Student":
cursor.execute("SELECT * FROM userlogin WHERE UserID=%s AND Password=%s
AND Type='Student'", (user_id, password))
elif user_type == "Teacher":
cursor.execute("SELECT * FROM userlogin WHERE UserID=%s AND Password=%s
AND Type='Teacher'", (user_id, password))
else:
cursor.execute("SELECT * FROM userlogin WHERE UserID=%s AND Password=%s
AND Type='Admin'", (user_id, password))
result = cursor.fetchone()
if result != None:
var1 = user_id # Set var1 to the logged-in user's ID
under_fm = tk.Frame(root, height=500, width=900, bg='#fff')
under_fm.place(x=0, y=0)
fm2 = tk.Frame(root, bg='#012727', height=80, width=900)
fm2.place(x=0, y=0)
lbb = tk.Label(fm2, bg='#012727')
lbb.place(x=15, y=5)
dashboard_label = tk.Label(canvas, text=f"Welcome, {var1}!", bg='black', fg='white',
font=('Arial', 16, 'bold'))
dashboard_label.place(x=200, y=100)
lb3 = tk.Label(fm2, text='DASHBOARD', fg='White', bg='#012727', font=('times new
roman', 30, 'bold'))
lb3.place(x=325, y=17)
name = tk.Label(root, text="WELCOME!", bg='#fff', fg="black", font=('Calibri', 12, 'bold'))
name.place(x=5, y=83)
today = date.today()
dat = tk.Label(root, text='Date : ', bg='#fff', fg='black', font=('Calibri', 12, 'bold'))
dat.place(x=750, y=83)
dat2 = tk.Label(root, text=today, bg='#fff', fg='black', font=('Calibri', 12, 'bold'))
dat2.place(x=800, y=83)
else:
messagebox.showerror('Library System', 'Your ID or Password is invalid!')
if result:
var1 = user_id # Set var1 to the logged-in user's ID
dashboard(user_type)
else:
messagebox.showerror('Library System', 'Your ID or Password is invalid!')
except mysql.connector.Error as err:
messagebox.showerror('Library System', f"Error: {err}")
finally:
if mydb.is_connected():
cursor.close()
mydb.close()
def dashboard(user_type):
if user_type == "Student":
show_student_dashboard()
elif user_type == "Teacher":
show_teacher_dashboard()
elif user_type == "Admin":
show_admin_dashboard()
# Student Dashboard Function
def show_student_dashboard():
# Create the frame for the dashboard first
fm3 = tk.Frame(root, bg='#fff', width=900, height=390)
fm3.place(x=0, y=110)
lb3_hr = tk.Label(fm3, text='05', font=('times new roman', 20, 'bold'), bg='#581845', fg='white')
lb3_hr.place(x=677, y=0, width=60, height=30)
lb5_hr = tk.Label(fm3, text='37', font=('times new roman', 20, 'bold'), bg='#581845', fg='white')
lb5_hr.place(x=747, y=0, width=60, height=30)
def clock():
h = str(time.strftime("%I")) # Use %I for 12-hour format
m = str(time.strftime("%M"))
s = str(time.strftime("%S"))
if int(h) >= 12:
lb7_hr.config(text="PM")
else:
lb7_hr.config(text="AM")
lb1_hr.config(text=h)
lb3_hr.config(text=m)
lb5_hr.config(text=s)
lb1_hr.after(200, clock) # Update every 200 ms
global photo9
# Add image
canvas8 = tk.Canvas(fm3, bg='black', width=400, height=300)
canvas8.place(x=475, y=40)
image_path = r"C:\Users\Admin\Downloads\stud.png"
photo9 = tk.PhotoImage(file=image_path)
canvas8.create_image(0, 0, image=photo9, anchor="nw")
# Developed By Label
develop = tk.Label(fm3, text='Developed By - <JK x AH>', bg='#fff', fg='#d7837f',
font=('Candara', 12, 'bold'))
develop.place(x=732, y=350)
# Button Configuration
button_config = {
'fg': '#fff',
'bg': '#581845',
'font': ('Candara', 15, 'bold'),
'width': 15,
'bd': 7,
'relief': 'flat',
'cursor': 'hand2',
'activebackground': 'black',
'activeforeground': '#581845'
}
lb3_hr = tk.Label(fm3, text='05', font=('times new roman', 20, 'bold'), bg='#581845', fg='white')
lb3_hr.place(x=677, y=0, width=60, height=30)
lb5_hr = tk.Label(fm3, text='37', font=('times new roman', 20, 'bold'), bg='#581845', fg='white')
lb5_hr.place(x=747, y=0, width=60, height=30)
def clock():
h = str(time.strftime("%I")) # Use %I for 12-hour format
m = str(time.strftime("%M"))
s = str(time.strftime("%S"))
if int(h) >= 12:
lb7_hr.config(text="PM")
else:
lb7_hr.config(text="AM")
lb1_hr.config(text=h)
lb3_hr.config(text=m)
lb5_hr.config(text=s)
lb1_hr.after(200, clock) # Update every 200 ms
# Developed By Label
develop = tk.Label(fm3, text='Developed By - <JK x AH>', bg='#fff', fg='#d7837f',
font=('Candara', 12, 'bold'))
develop.place(x=732, y=350)
# Button Configuration
button_config = {
'fg': '#fff',
'bg': '#581845',
'font': ('Candara', 15, 'bold'),
'width': 15,
'bd': 7,
'relief': 'flat',
'cursor': 'hand2',
'activebackground': 'black',
'activeforeground': '#581845'
}
lb3_hr = tk.Label(fm3, text='05', font=('times new roman', 20, 'bold'), bg='#581845', fg='white')
lb3_hr.place(x=677, y=0, width=60, height=30)
lb5_hr = tk.Label(fm3, text='37', font=('times new roman', 20, 'bold'), bg='#581845', fg='white')
lb5_hr.place(x=747, y=0, width=60, height=30)
def clock():
h = str(time.strftime("%I")) # Use %I for 12-hour format
m = str(time.strftime("%M"))
s = str(time.strftime("%S"))
if int(h) >= 12:
lb7_hr.config(text="PM")
else:
lb7_hr.config(text="AM")
lb1_hr.config(text=h)
lb3_hr.config(text=m)
lb5_hr.config(text=s)
lb1_hr.after(200, clock) # Update every 200 ms
# Developed By Label
develop = tk.Label(fm3, text='Developed By - <JK x AH>', bg='#fff', fg='#d7837f',
font=('Candara', 12, 'bold'))
develop.place(x=732, y=350)
# Button Configuration
button_config = {
'fg': '#fff',
'bg': '#581845',
'font': ('Candara', 15, 'bold'),
'width': 15,
'bd': 7,
'relief': 'flat',
'cursor': 'hand2',
'activebackground': 'black',
'activeforeground': '#581845'
}
def addbooks():
bid = input("Enter book ID: ")
tit = input("Enter title of the book: ")
aut = input("Enter author name: ")
pub = input("Enter publication: ")
st = input("Enter status (No of Books Available): ")
gen = input("Enter genre: ")
pr = float(input("Enter price: "))
q = "INSERT INTO book VALUES('{}', '{}', '{}', '{}', '{}', '{}', {})".format(bid, tit, aut, pub, st, gen,
pr)
try:
mycur.execute(q)
con.commit()
print("BOOK ADDED SUCESSFULLY")
except mysql.connector.Error as err:
print(f"Error: {err}")
def updatebooks():
print("1. Update based on title")
print("2. Update based on book ID")
op = int(input("Enter your option: "))
if op == 1:
book_title = input("Enter the book title: ")
new_author = input("Enter the new author: ")
new_publication = input("Enter the new publication: ")
new_stval = input("Enter new stock value: ")
new_gen = input("Enter your new genre: ")
new_price = float(input("Enter the new price: "))
q = "UPDATE book SET author='{}', publication='{}', status='{}', genre='{}', price={} WHERE
title='{}'".format(new_author, new_publication, new_stval, new_gen, new_price, book_title)
mycur.execute(q)
con.commit()
print("The BOOK is updated successfully!")
elif op == 2:
book_id = input("Enter the book ID: ")
new_author = input("Enter the new author: ")
new_publication = input("Enter the new publication: ")
new_stval = input("Enter new stock value: ")
new_gen = input("Enter your new genre: ")
new_price = float(input("Enter the new price: "))
q = "UPDATE book SET author='{}', publication='{}', status='{}', genre='{}', price={} WHERE
book_id='{}'".format(new_author, new_publication, new_stval, new_gen, new_price,
book_id)
mycur.execute(q)
con.commit()
print("The BOOK is updated successfully!")
for i in d1:
if i[0] == book_id and i[1] == teacher_id:
res = (datetime.strptime(str(i[3]), "%Y-%m-%d") - datetime.strptime(str(cur_date),
"%Y-%m-%d")).days
if res >= 0:
print("Book is returned on time.")
q3 = "UPDATE booktransact SET status='R' WHERE book_id='{}' and
person_id='{}'".format(book_id, teacher_id)
mycur.execute(q3)
con.commit()
q4 = "UPDATE book SET status=status+1 WHERE book_id='{}'".format(book_id)
mycur.execute(q4)
con.commit()
else:
print("You have to pay a fine of Rs", math.fabs(res) * 10, "for", math.fabs(res), "days.")
break
else:
print("Invalid entry.")
def removebooks():
print("1. Remove based on bookid")
print("2. Remove based on title")
op = int(input("Enter your option: "))
if op == 1:
bid = input("Enter bookid to be removed: ")
q = "DELETE FROM book WHERE book_id='{}'".format(bid)
mycur.execute(q)
con.commit()
print("The book is removed successfully!")
elif op == 2:
tit = input("Enter title of the book: ")
q = "DELETE FROM book WHERE title ='{}'".format(tit)
mycur.execute(q)
con.commit()
print("The book is removed successfully!")
from tabulate import tabulate
def viewbooks():
mycur.execute("SELECT book_id, title, author, publication, status, genre, price FROM book")
a = mycur.fetchall()
headers = ["ID", "Title", "Author", "Publication", "Status", "Genre", "Price"]
print(tabulate(a, headers=headers, tablefmt="grid", stralign="center", numalign="center"))
def viewstudent():
q = "SELECT * FROM student"
mycur.execute(q)
students_data = mycur.fetchall()
column_names = [desc[0] for desc in mycur.description]
print(tabulate(students_data, headers=column_names, tablefmt="fancy_grid"))
def viewteacher():
q = "SELECT * FROM teacher"
mycur.execute(q)
teachers_data = mycur.fetchall()
column_names = [desc[0] for desc in mycur.description]
print(tabulate(teachers_data, headers=column_names, tablefmt="fancy_grid"))
def view_book_transactions():
q = "SELECT book_id, person_id, issue_date, return_date, status FROM booktransact"
mycur.execute(q)
transactions_data = mycur.fetchall()
column_names = ["Book ID", "Person ID", "Issue Date", "Return Date", "Status"]
print(tabulate(transactions_data, headers=column_names, tablefmt="grid", stralign="center",
numalign="center"))
def on_closing(window):
# Close the connection if no other windows are open
if len(root.winfo_children()) == 1: # Assuming 'root' is your main Tk window
mycur.close()
connection.close()
window.destroy()
def bookdet():
ans = 'y'
while ans == "y":
print("1. Add book")
print("2. Remove book")
print("3. Update book")
print("4. View book details")
print("5. View book transaction list")
print("6. Go to main menu")
x = int(input("Enter your option: "))
if x == 1:
addbooks()
if x == 2:
removebooks()
if x == 3:
updatebooks()
if x == 4:
viewbooks()
if x == 5:
view_book_transactions()
if x == 6:
break
ans = input("Do you want to continue (y/n)? ")
def studet():
ans = 'y'
while ans == 'y':
print("1. Register Student ")
print("2. Remove Student details ")
print("3. View Student details ")
print("4. Go to Main Menu ")
x = int(input("Enter your option: "))
if x == 1:
addstudent()
if x == 2:
removestudent()
if x == 3:
viewstudent()
if x == 4:
break
ans = input("Do you want to continue (y/n)? ")
def teadet():
ans = 'y'
while ans == 'y':
print("1. Register Teacher ")
print("2. Remove Teacher details ")
print("3. View Teacher details ")
print("4. Go to Main Menu ")
x = int(input("Enter your option: "))
if x == 1:
addteacher()
if x == 2:
removeteacher()
if x == 3:
viewteacher()
if x == 4:
break
ans = input("Do you want to continue (y/n)? ")
def addstudent():
sid = input("Enter student ID: ")
name = input("Enter student name: ")
cl = input("Enter class: ")
sec = input("Enter section: ")
q = "INSERT INTO student VALUES('{}', '{}', '{}', '{}')".format(sid, name, cl, sec)
mycur.execute(q)
con.commit()
print("STUDENT ADDED SUCCESSFULLY")
def removestudent():
sid = input("Enter student ID to be removed: ")
q = "DELETE FROM student WHERE stud_id='{}'".format(sid)
mycur.execute(q)
con.commit()
print("STUDENT REMOVED SUCCESFULLY")
def updatestudent():
sid = input("Enter student ID: ")
new_name = input("Enter new name: ")
new_cl = input("Enter new class: ")
new_sec = input("Enter new section: ")
q = "UPDATE student SET name='{}', class='{}', sec='{}' WHERE
stud_id='{}'".format(new_name, new_cl, new_sec, sid)
mycur.execute(q)
con.commit()
print("Successfully updated student information.")
def addteacher():
tid = input("Enter teacher ID: ")
name = input("Enter teacher name: ")
dep = input("Enter department: ")
q = "INSERT INTO teacher VALUES('{}', '{}', '{}')".format(tid, name, dep)
mycur.execute(q)
con.commit()
print("Successfully added teacher.")
def removeteacher():
print("1. Remove based on teacher ID")
teacher_id = input("Enter teacher ID to be removed: ")
q = "DELETE FROM teacher WHERE teacher_id='{}'".format(teacher_id)
mycur.execute(q)
con.commit()
print("Successfully removed teacher.")
def updateteacher():
print("Update using teacher ID")
tid = input("Enter teacher ID: ")
new_name = input("Enter new teacher name: ")
new_dep = input("Enter new department name: ")
q = "UPDATE teacher SET name='{}', department='{}' WHERE
teacher_id='{}'".format(new_name, new_dep, tid)
mycur.execute(q)
con.commit()
print("Successfully updated teacher information.")
def reports():
ans = "y"
while ans == "y":
print("1. BOOK wise report")
print("2. STUDENT wise report")
print("3. TEACHER wise report")
print("4. Go back to main menu")
op = int(input("Enter your option: "))
if op == 1:
bookwise()
elif op == 2:
studentwise()
elif op == 3:
teacherwise()
elif op == 4:
break
ans = input("Do you want to continue (y/n) in the report menu? ")
def bookwise():
bid = int(input("Enter the book ID: "))
q1 = "SELECT * FROM booktransact WHERE book_id={}".format(bid)
try:
mycur.execute(q1)
a = mycur.fetchall()
for i in a:
print(i)
except mysql.connector.Error as err:
print(f"Error: {err}")
def studentwise():
sid = input("Enter the student ID: ")
q2 = "SELECT * FROM booktransact WHERE person_id='{}'".format(sid)
mycur.execute(q2)
c = mycur.fetchall()
for i in c:
print(i)
def teacherwise():
tid = input("Enter the teacher ID: ")
q2 = "SELECT * FROM booktransact WHERE person_id='{}'".format(tid)
mycur.execute(q2)
c = mycur.fetchall()
for i in c:
print(i)
def logout():
for widget in root.winfo_children():
widget.destroy()
logout_label = tk.Label(root, text="You have logged out. \n Happy to Help You\n Developed
By Jaishree.K and Harsine", font=("Arial", 16))
logout_label.pack(pady=20)
root.after(2000, show_dashboard)
# Main Tkinter setup
root = tk.Tk()
root.title("Library Management System")
root.geometry("900x500")
root.configure(bg='black')
----------------------------------------------------------------xxx----------------------------------------------------------------------
STUDENT / TEACHER DASHBOARD
ADMIN DASHBOARD:
STUDENT DASHBOARD:
ISSUE BOOKS:
UPDATE DETAILS:
RETURN BOOKS:
TEACHER DASHBOARD:
ISSUE BOOKS:
RETURN BOOKS:
UPDATE DETAILS:
FUNCTIONS USED: