Source Code (2)
Source Code (2)
2
3
4
5
FUNCTIONS USED:
6
addstudent(): Adds a new student record to the system’s
database.
7
MODULES USED:
TKINTER:
Tkinter is Python’s standard library for creating graphical
user interfaces(GUIs).It provides a variety of widgets
(Buttons,labels,text fields,etc.) to build interactive
applications.The layout is managed using Tkinter frames
and canvases creating an intuitive experience for both
users and administrators.
MySQL Connector:
The MySQL connector module allows Python to interact
with MySQL databases. It supports operations like
creating and modifying tables, inserting data, and
querying information. Through SQL queries,it enables
efficient data management and ensures the application
remains responsive by fetching only necessary data.
Datetime:
Datetime module provides classes for handling dates and
times in python. It’s useful for calculating durations.
Tabulate:
Tabulate library in Python to create well-formatted
tables
8
SOURCE CODE
import tkinter as tk
from tkinter import messagebox
import mysql.connector
from datetime import datetime
from prettytable import PrettyTable
import math
# 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
9
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)
10
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)
# Password
password_label = tk.Label(root, text='Password', bg='black', font=('Arial', 12, 'bold'),
fg='white')
password_label.place(x=200, 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)
11
# 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)
12
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)
def login():
global user_type_var
user_type_var = tk.StringVar(value="student")
13
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)
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")
14
new_window.geometry("350x500")
new_window.configure(bg='#e7f3fe')
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()
15
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')
16
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)
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()
17
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)
18
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"
)
19
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)
20
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()
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',
21
'bg': '#581845',
'font': ('Candara', 15, 'bold'),
'width': 15,
'bd': 7,
'relief': 'flat',
'cursor': 'hand2',
'activebackground': 'black',
'activeforeground': '#581845'
}
22
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")
# Button Configuration
button_config = {
'fg': '#fff',
'bg': '#581845',
'font': ('Candara', 15, 'bold'),
'width': 15,
'bd': 7,
'relief': 'flat',
'cursor': 'hand2',
'activebackground': 'black',
'activeforeground': '#581845'
}
23
# Create the frame for the dashboard first
fm3 = tk.Frame(root, bg='#fff', width=900, height=390)
fm3.place(x=0, y=110)
# 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',
24
'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}")
25
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.")
26
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: ")
27
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.")
28
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.")
29
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]
30
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
31
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():
32
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)
33
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()
34
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----------------------------------------------------------------------
35
OUTPUT
36
STUDENT / TEACHER DASHBOARD
37
ADMIN DASHBOARD:
MYSQL DATABASES
38
39
ADMIN BOOK DETAILS:
40
41
ADMIN TEACHER DETAILS:
42
REPORT GENERATION:
STUDENT DASHBOARD:
ISSUE BOOKS:
UPDATE DETAILS:
RETURN BOOKS:
43
TEACHER DASHBOARD:
ISSUE BOOKS:
RETURN BOOKS:
UPDATE DETAILS:
44
BIBLIOGRAPHY
COMPUTER SCIENCE WITH PYTHON - SUMITA ARORA
WIKIPEDIA
https://www.geeksforgeeks.org/
https://www.youtube.com/
https://stackoverflow.com/
45