0% found this document useful (0 votes)
2 views

Source Code

The document outlines the hardware and software requirements for a Python application that connects to a MySQL database. It includes a detailed description of the system specifications, the source code for a GUI application using Tkinter, and various functions for user login, signup, and database operations. Additionally, it provides a structure for user interaction and data management within the application.

Uploaded by

keerthana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Source Code

The document outlines the hardware and software requirements for a Python application that connects to a MySQL database. It includes a detailed description of the system specifications, the source code for a GUI application using Tkinter, and various functions for user login, signup, and database operations. Additionally, it provides a structure for user interaction and data management within the application.

Uploaded by

keerthana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

● REQUIREMENT

● 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)

canvas = tk.Canvas(root, height=500, width=900)


canvas.pack()

# Display the background image


canvas.create_image(0, 0, anchor=tk.NW, image=bg_image)
overlay_image = Image.new('RGBA', (900, 500), (0, 0, 0, 180))
overlay = ImageTk.PhotoImage(overlay_image)
canvas.create_image(0, 0, anchor=tk.NW, image=overlay)
enchanted_quote = tk.Label(canvas, text="Unlock the gates to the library of wonders,
\nwhere 'The Hobbit' meets 'Harry Potter', and 'Pride and Prejudice' dances with 'The Great
Gatsby'.\n Step through the portals of wisdom where 'Verity' uncovers truths, 'Percy
Jackson' wields mythical powers,\n beckoning you to explore realms beyond imagination.",
fg='white', bg='black', font=('Arial', 10, 'italic'))
enchanted_quote.place(x=60, y=60)

lets_go_button = tk.Button(canvas, text="Let's Go", fg='black', bg='yellow', width=15,


font=('Arial', 12, 'bold'), activebackground='black',
activeforeground='yellow', command=show_dashboard, bd=3, relief='flat',
cursor='hand2')
lets_go_button.place(x=340, y=380)

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)

user_entry = tk.Entry(root, width=22, font=('Arial', 12, 'bold'), bd=4, relief='groove')


user_entry.place(x=320, y=100)
# Password
password_label = tk.Label(root, text='Password', bg='black', font=('Arial', 12, 'bold'),
fg='white')
password_label.place(x=200, y=150)

password_entry = tk.Entry(root, width=22, show='*', font=('Arial', 12, 'bold'), bd=4,


relief='groove')
password_entry.place(x=320, y=150)

# 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)

# Forgot Password Button


forgot_password_button = tk.Button(root, text='Forgot Password', fg='black', bg='orchid1',
width=15, font=('Arial', 10, 'bold'),
activebackground='purple', activeforeground='yellow', bd=3, relief='flat',
cursor='hand2',
command=forgot_password)
forgot_password_button.place(x=320, y=350)

right_image = Image.open(r"C:\Users\Admin\Downloads\right.png").resize((250, 400))


right_image = ImageTk.PhotoImage(right_image)
right_image_label = tk.Label(canvas, image=right_image, bg='white')
right_image_label.image = right_image
right_image_label.place(x=600, y=50)

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)

user_type_student = tk.Radiobutton(canvas, text='Student', variable=user_type_var,


value='Student',
bg='grey33', fg='white', font=('Arial', 12, 'bold'),
activebackground='black', activeforeground='white',
selectcolor='purple1')
user_type_student.place(x=300, y=200)

user_type_teacher = tk.Radiobutton(canvas, text='Teacher', variable=user_type_var,


value='Teacher',
bg='grey33', fg='white', font=('Arial', 12, 'bold'),
activebackground='black', activeforeground='white',
selectcolor='purple1')
user_type_teacher.place(x=400, y=200)

user_type_admin = tk.Radiobutton(canvas, text='Admin', variable=user_type_var,


value='Admin',
bg='grey33', fg='white', font=('Arial', 12, 'bold'),
activebackground='black', activeforeground='white',
selectcolor='purple1')
user_type_admin.place(x=500, y=200)

btn3 = tk.Button(canvas, text='Sign Up', fg='black', bg='yellow', width=10, font=('Arial', 12,


'bold'),
activebackground='black', activeforeground='yellow', bd=3, relief='flat',
cursor='hand2',
command=signup)
btn3.place(x=220, y=300)

def login():
global user_type_var
user_type_var = tk.StringVar(value="student")

# Create login window


login_window = tk.Toplevel(root)
login_window.title("Login")
login_window.geometry("300x200")
login_window.configure(bg='#f0f0f0')

tk.Label(login_window, text="User ID:", bg='#f0f0f0').pack(pady=5)


user_id_entry = tk.Entry(login_window)
user_id_entry.pack(pady=5)

tk.Label(login_window, text="Password:", bg='#f0f0f0').pack(pady=5)


password_entry = tk.Entry(login_window, show='*')
password_entry.pack(pady=5)
tk.Button(login_window, text="Login", command=lambda: process_login(user_id_entry.get(),
password_entry.get()),
bg='#4CAF50', fg='white').pack(pady=20)

tk.Button(login_window, text="Sign Up", command=signup,


bg='#2196F3', fg='white').pack(pady=5)

def process_login(user_id, password):


global user_type_var
user_type = user_type_var.get()
if user_id and password:
open_dashboard(user_id)
else:
messagebox.showerror("Login Error", "Please enter User ID and Password.")

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)

tk.Radiobutton(new_window, text="Student", variable=user_type_var, value="student",


bg='#f0f0f0',
font=('Arial', 12), fg='#333').pack()
tk.Radiobutton(new_window, text="Teacher", variable=user_type_var, value="teacher",
bg='#f0f0f0',
font=('Arial', 12), fg='#333').pack()

tk.Button(new_window, text="Next", command=lambda: show_form(new_window,


user_type_var.get()),
bg='#4CAF50', fg='white', font=('Arial', 12, 'bold')).pack(pady=20)

def show_form(window, user_type):


window.destroy()
if user_type == "student":
open_student_form()
else:
open_teacher_form()
def open_student_form():
global stud_id, name, stud_class, section, user_id, password
new_window = tk.Toplevel(root)
new_window.title("Student Sign Up")
new_window.geometry("350x500")
new_window.configure(bg='#e7f3fe')

tk.Label(new_window, text="Student ID:", bg='#e7f3fe', font=('Arial', 12)).pack(pady=5)


stud_id = tk.Entry(new_window, bd=2, font=('Arial', 12))
stud_id.pack(pady=5)

tk.Label(new_window, text="Name:", bg='#e7f3fe', font=('Arial', 12)).pack(pady=5)


name = tk.Entry(new_window, bd=2, font=('Arial', 12))
name.pack(pady=5)

tk.Label(new_window, text="Class:", bg='#e7f3fe', font=('Arial', 12)).pack(pady=5)


stud_class = tk.Entry(new_window, bd=2, font=('Arial', 12))
stud_class.pack(pady=5)

tk.Label(new_window, text="Section:", bg='#e7f3fe', font=('Arial', 12)).pack(pady=5)


section = tk.Entry(new_window, bd=2, font=('Arial', 12))
section.pack(pady=5)

tk.Label(new_window, text="User ID:", bg='#e7f3fe', font=('Arial', 12)).pack(pady=5)


user_id = tk.Entry(new_window, bd=2, font=('Arial', 12))
user_id.pack(pady=5)

tk.Label(new_window, text="Password:", bg='#e7f3fe', font=('Arial', 12)).pack(pady=5)


password = tk.Entry(new_window, bd=2, show="*", font=('Arial', 12))
password.pack(pady=5)

submit_btn = tk.Button(new_window, text="Submit", command=submit_student_form,


bg='#4CAF50',
fg='white', font=('Arial', 12, 'bold'))
submit_btn.pack(pady=10)

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')

tk.Label(new_window, text="Teacher ID:", bg='#e7f3fe', font=('Arial', 12)).pack(pady=5)


teacher_id = tk.Entry(new_window, bd=2, font=('Arial', 12))
teacher_id.pack(pady=5)

tk.Label(new_window, text="Name:", bg='#e7f3fe', font=('Arial', 12)).pack(pady=5)


name = tk.Entry(new_window, bd=2, font=('Arial', 12))
name.pack(pady=5)

tk.Label(new_window, text="Department:", bg='#e7f3fe', font=('Arial', 12)).pack(pady=5)


department = tk.Entry(new_window, bd=2, font=('Arial', 12))
department.pack(pady=5)

tk.Label(new_window, text="User ID:", bg='#e7f3fe', font=('Arial', 12)).pack(pady=5)


user_id = tk.Entry(new_window, bd=2, font=('Arial', 12))
user_id.pack(pady=5)

tk.Label(new_window, text="Password:", bg='#e7f3fe', font=('Arial', 12)).pack(pady=5)


password = tk.Entry(new_window, bd=2, show="*", font=('Arial', 12))
password.pack(pady=5)

submit_btn = tk.Button(new_window, text="Submit", command=submit_teacher_form,


bg='#2196F3',
fg='white', font=('Arial', 12, 'bold'))
submit_btn.pack(pady=10)

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)

tk.Label(new_window, text="Name:", bg='#f0e68c', font=('Arial', 12)).pack(pady=5)


name_entry = tk.Entry(new_window, bd=2, font=('Arial', 12))
name_entry.pack(pady=5)
tk.Label(new_window, text="User ID:", bg='#f0e68c', font=('Arial', 12)).pack(pady=5)
user_id_entry = tk.Entry(new_window, bd=2, font=('Arial', 12))
user_id_entry.pack(pady=5)

# New Password Entry


tk.Label(new_window, text="New Password:", bg='#f0e68c', font=('Arial', 12)).pack(pady=5)
new_password_entry = tk.Entry(new_window, bd=2, font=('Arial', 12), show='*')
new_password_entry.pack(pady=5)

tk.Label(new_window, text="Confirm Password:", bg='#f0e68c', font=('Arial',


12)).pack(pady=5)
confirm_password_entry = tk.Entry(new_window, bd=2, font=('Arial', 12), show='*')
confirm_password_entry.pack(pady=5)

submit_btn = tk.Button(new_window, text="Reset Password", command=lambda:


reset_password(name_entry.get(), user_id_entry.get(), new_password_entry.get(),
confirm_password_entry.get()),bg='yellow', fg='black', font=('Arial', 12))
submit_btn.pack(pady=20)

def reset_password(name, user_id, new_password, confirm_password):


if new_password != confirm_password:
messagebox.showerror("Error", "Passwords do not match.")
return
conn = database()
cursor = conn.cursor()

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.")

except mysql.connector.Error as err:


messagebox.showerror("Database Error", f"Error: {err}")

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)

# Create labels to display the time


lb1_hr = tk.Label(fm3, text='12', font=('times new roman', 20, 'bold'), bg='#581845', fg='white')
lb1_hr.place(x=607, y=0, width=60, height=30)

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)

lb7_hr = tk.Label(fm3, text='AM', font=('times new roman', 17, 'bold'), bg='#581845',


fg='white')
lb7_hr.place(x=817, 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

clock() # Start the clock function

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'
}

# Issue Book Button


bt1 = tk.Button(fm3, text=' Issue Books', command=issuebooks, **button_config)
bt1.place(x=40, y=40)

# Return Book Button


bt2 = tk.Button(fm3, text=' Return Books', command=returnbooks, **button_config)
bt2.place(x=250, y=40)

# View Books Button


bt3 = tk.Button(fm3, text=' View Books', command=viewbooks, **button_config)
bt3.place(x=40, y=120)
#view_button.pack()

# Update Details Button


bt4 = tk.Button(fm3, text='Update details', command=updatestudent, **button_config)
bt4.place(x=250, y=120)

# Log Out Button


bt5 = tk.Button(fm3, text=' Log out', command=logout, **button_config)
bt5.place(x=40, y=200)

# Teacher Dashboard Function


def show_teacher_dashboard():
# Create the frame for the dashboard first
fm3 = tk.Frame(root, bg='#fff', width=900, height=390)
fm3.place(x=0, y=110)

# Create labels to display the time


lb1_hr = tk.Label(fm3, text='12', font=('times new roman', 20, 'bold'), bg='#581845', fg='white')
lb1_hr.place(x=607, y=0, width=60, height=30)

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)

lb7_hr = tk.Label(fm3, text='AM', font=('times new roman', 17, 'bold'), bg='#581845',


fg='white')
lb7_hr.place(x=817, 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

clock() # Start the clock function


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'
}

# Issue Book Button


bt1 = tk.Button(fm3, text=' Issue Books', command=issuebook, **button_config)
bt1.place(x=40, y=40)

# Return Book Button


bt2 = tk.Button(fm3, text=' Return Books', command=returnbook, **button_config)
bt2.place(x=250, y=40)

# View Books Button


bt3 = tk.Button(fm3, text=' View Books', command=viewbooks, **button_config)
bt3.place(x=40, y=120)

# Update Details Button


bt4 = tk.Button(fm3, text='Update details', command=updateteacher, **button_config)
bt4.place(x=250, y=120)

# Log Out Button


bt5 = tk.Button(fm3, text=' Log out', command=logout, **button_config)
bt5.place(x=40, y=200)

# Admin Dashboard Function


def show_admin_dashboard():
# Create the frame for the dashboard first
fm3 = tk.Frame(root, bg='#fff', width=900, height=390)
fm3.place(x=0, y=110)

# Create labels to display the time


lb1_hr = tk.Label(fm3, text='12', font=('times new roman', 20, 'bold'), bg='#581845', fg='white')
lb1_hr.place(x=607, y=0, width=60, height=30)

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)

lb7_hr = tk.Label(fm3, text='AM', font=('times new roman', 17, 'bold'), bg='#581845',


fg='white')
lb7_hr.place(x=817, 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

clock() # Start the clock function


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'
}

# Add Book Button


bt1 = tk.Button(fm3, text=' Book Details', command=bookdet, **button_config)
bt1.place(x=40, y=40)

# Student Details Button


bt2 = tk.Button(fm3, text=' Student Details', command=studet, **button_config)
bt2.place(x=250, y=40)

# Teacher Details Button


bt3 = tk.Button(fm3, text=' Teacher Details', command=teadet, **button_config)
bt3.place(x=40, y=120)

# Report Generation Button


bt4 = tk.Button(fm3, text='Report Generation', command=reports, **button_config)
bt4.place(x=250, y=120)

# Log Out Button


bt5 = tk.Button(fm3, text=' Logout', command=logout, **button_config)
bt5.place(x=40, y=200)

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 issuebook(): # FOR TEACHER


book_id = int(input("Enter the book ID: "))
q = "SELECT * FROM book"
mycur.execute(q)
data = mycur.fetchall()
for i in data:
if i[0] == book_id:
teacher_id = input("Enter your teacher ID: ")
issue_date = datetime.now().date()
return_date = (datetime.now() + timedelta(days=7)).date()
q1 = "SELECT * FROM teacher"
mycur.execute(q1)
d = mycur.fetchall()
for j in d:
if j[0] == teacher_id:
if i[4] != 0:
print("The book is issued.")
print("The book should be returned on or before", return_date)
val = int(i[4]) - 1
q2 = "UPDATE book SET status={} WHERE book_id='{}'".format(val, book_id)
mycur.execute(q2)
con.commit()
status = "I"
q3 = "INSERT INTO booktransact VALUES('{}', '{}', '{}', '{}','{}')".format(book_id,
teacher_id, issue_date, return_date, status)
mycur.execute(q3)
con.commit()
else:
print("The book is not available.")
break
else:
print("You have not registered. Please register and start.")
break
else:
print("You have entered an invalid book ID.")
def issuebooks(): # FOR STUDENT
book_id = int(input("Enter the book ID: "))
q = "SELECT * FROM book"
mycur.execute(q)
data = mycur.fetchall()
for i in data:
if i[0] == book_id:
student_id = input("Enter your student ID: ")
issue_date = datetime.now().date()
return_date = (datetime.now() + timedelta(days=7)).date()
q1 = "SELECT * FROM student"
mycur.execute(q1)
d = mycur.fetchall()
for j in d:
if j[0] == student_id:
if i[4] != 0:
print("The book is issued.")
print("The book should be returned on or before", return_date)
val = int(i[4]) - 1
q2 = "UPDATE book SET status={} WHERE book_id='{}'".format(val, book_id)
mycur.execute(q2)
con.commit()
status = "I"
q3 = "INSERT INTO booktransact VALUES('{}', '{}', '{}', '{}','{}')".format(book_id,
student_id, issue_date, return_date, status)
mycur.execute(q3)
con.commit()
else:
print("The book is not available.")
break
else:
print("You have not registered. Please register and start.")
break
else:
print("You have entered an invalid book ID.")

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!")

def returnbook(): # FOR TEACHER


book_id = input("Enter the book ID: ")
teacher_id = input("Enter your teacher ID: ")
cur_date = datetime.now().date()
q2 = "SELECT * FROM booktransact"
mycur.execute(q2)
d1 = mycur.fetchall()

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 returnbooks(): # FOR STUDENT


book_id = input("Enter the book ID: ")
student_id = input("Enter your student ID: ")
cur_date = datetime.now().date()
q2 = "SELECT * FROM booktransact"
mycur.execute(q2)
d1 = mycur.fetchall()
for i in d1:
if i[0] == book_id and i[1] == student_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, student_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')

# Initialize the main frame


main() # Start the application
root.mainloop() # Run the application

----------------------------------------------------------------xxx----------------------------------------------------------------------
STUDENT / TEACHER DASHBOARD
ADMIN DASHBOARD:

AFTER CLICKING ‘Logout’ BUTTON:


ADMIN BOOK DETAILS:
ADMIN TEACHER DETAILS:

ADMIN STUDENT DETAILS:


REPORT GENERATION:

STUDENT DASHBOARD:
ISSUE BOOKS:

UPDATE DETAILS:

RETURN BOOKS:
TEACHER DASHBOARD:
ISSUE BOOKS:

RETURN BOOKS:

UPDATE DETAILS:
FUNCTIONS USED:

bookwise(): Provides reports based on specific books,


showing all the necessary details.

studentwise(): Generates reports based on individual


student data, including borrowing history,whether they issued
the book or not.

teacherwise(): Creates reports centered on teacher


records, including books borrowed.

removebooks(): Removes a book's record from the library’s


database.

addbooks(): Adds new books to the library’s collection.

updatebooks(): Updates existing information for books in the


library database. Only applicable for ADMIN

viewbooks(): Displays all books currently in the library’s


collection.

returnbooks(): Processes book returns and updates records


accordingly.

view_book_transactions(): Shows the transaction history


of books issued and returned.
addstudent(): Adds a new student record to the system’s
database.

removestudent(): Removes a student's record from the


library database.

updatestudent(): Updates details for an existing student


record.

addteacher(): Adds a new teacher record to the library


system.

removeteacher(): Removes a teacher’s record from the


library database.

updateteacher(): Updates information for an existing


teacher record.
BIBLIOGRAPHY
COMPUTER SCIENCE WITH PYTHON - SUMITA ARORA
WIKIPEDIA
GOOGLE

You might also like