0% found this document useful (0 votes)
10 views58 pages

Group 8 Project

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views58 pages

Group 8 Project

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

CHETTINAD VIDYASHRAM

COMPUTER SCIENCE PROJECT


STD XII (2024-25)

HORMIS
DEVESH
CHAITESH
AYMAN

XII-C

HOSPITAL MANAGEMENT
SYSTEM

1
ACKNOWLEDGEMENT

I would like to express my sincere thanks to Meena


Aunty, Principal Mrs. S.Amudhalakshmi for their
encouragement and support to work on this Project.
I am grateful to my computer science teacher Uma
Mageswari R and to the computer science
department for the constant guidance and support
to complete the project.

2
3
S.NO TOPIC PG.NO
1 Python overview 5

2 Python description 6

3 User defined functions 7

4 Tables used 9

5 Source code 11

6 Sample outputs 50

7 Conclusion 57

8 Bibliography 58

4
PYTHON OVERVIEW
Python is a high-level, interpreted, interactive and object-oriented scripting
language. Python is designed to be highly readable. It uses English keywords
frequently where as other languages use punctuation, and it has fewer
syntactical constructions than other languages.
Python is Interpreted - Python is processed at runtime by the interpreter. You
do not need to compile your program before executing it. This is similar to
PERL and PHP.
Python is Interactive - You can actually sit at a Python prompt and interact
with the interpreter directly to write your programs.
Python is Object-Oriented - Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
Python is a Beginner's Language - Python is a great language for the
beginner- level programmers and supports the development of a wide range of
applications from simple text processing to WWW browsers to games.
Python's features include -
Easy-to-learn- Python has few keywords, simple structure, and a clearly
defined syntax. This allows the student to pick up the language quickly. Easy-
to-read-Python code is more clearly defined and visible to the eyes. Easy-to-
maintain - Python's source code is fairly easy-to-maintain.
A broad standard library - Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode - Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
Portable - Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
Databases-Python provides interfaces to all major commercial databases.
GUI Programming - Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows
MFC, Macintosh, and the X Window system of Unix.

5
Scalable - Python provides a better structure and support for large
programs than shell scripting.
Other features:
It supports functional and structured programming methods as well as
OOP.
It can be used as a scripting language or can be compiled to byte-code
for building large applications.
It provides very high-level dynamic data types and supports dynamic
type checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and
Java.

PROJECT DESCRIPTION
Our project titled "Hospital management system" provides a GUI
based system to efficiently manage a Hospital’s network. We have
used a combination of Python and MySQL for the back-end code and
have designed a simple yet robust front-end GUI using Tkinter. Our
appropriate pop-up messages for various scenarios helps the user
understand what they have done to the database. The system runs
without any glitches at an optimal speed. This application facilitates
the user to manage a hospital’s network without clashes, update and
view the same in a much easier way.

6
FUNCTION PURPOSE
manage_patient() Opens the main window for managing patient records
with various operations.
insert_patient() Opens a window to admit a new patient and insert their
details into the database.
update_patient() Opens a window to update an existing patient's details in
the database.
delete_patient() Opens a window to discharge a patient and calculate
their bill based on days admitted.
display_patients() Opens a window to display all patient records in a table
format.

sort_patients() Opens a window to sort and view patient records by


specified fields like age or date of admission.
available_rooms() Opens a window to manage room occupancy by viewing,
occupying, or unoccupying available rooms.
update_room_status(action, Updates a specific room's status to either occupied or
room_number) unoccupied based on action.

display_rooms() Displays a list of all available and occupied rooms in a


table format.
manage_doctor() Opens the main window to manage doctor records,
providing options to insert, update, delete, display, and
sort doctors.
insert_doctor() Creates a window to add a new doctor record, taking
inputs for all doctor attributes and storing them in the
database.
submit() (inside Inserts a new doctor record into the database or displays
insert_doctor) an error if there’s an issue with the input.
sort_doctors() Opens a sorting window allowing users to sort doctor
records by either experience or date of joining.
sort_by(column_name) Fetches and displays doctor records sorted by the
specified column.
update_doctor(): Opens a window to update an existing doctor's details
based on their serial number.

submit() (inside Updates the doctor record in the database with the
update_doctor) provided details or shows an error if unsuccessful.
delete_doctor(): Opens a window to delete a doctor record based on the
serial number.
submit() (inside Deletes the specified doctor record from the database or
delete_doctor): displays a message if the record is not found.

7
display_doctors(): Fetches and displays all doctor records from the
database in a table format.
manage_medicine() Opens the main window to manage medicine records,
with options to insert, update, delete, and display
medicines.

insert_medicine() Opens a window to add a new medicine record by taking


input for all medicine attributes.
submit() (inside Inserts the new medicine record into the database.
insert_medicine)
update_medicine() Opens a window to update an existing medicine's details.
submit() (inside Updates the medicine record in the database with the
update_medicine) provided details.
delete_medicine(): Opens a window to delete a medicine record based on
the serial number.
submit() (inside Deletes the specified medicine record from the database.
delete_medicine)
display_medicines() Fetches and displays all medicine records from the
database in a table format.

8
TABLES USED
Table:Patient
Purpose:To store patient details

Table:Medicine
Purpose:To store medicine details

Table:Rooms
Purpose:To store available rooms.

9
Table:doctors
Purpose:To store doctor details

10
SOURCE CODE
import tkinter as tk
from tkinter import messagebox
from tkinter import ttk
from datetime import datetime
import mysql.connector

# Connection to MySQL database


mycon = mysql.connector.connect(
host="localhost",
user="root",
password="root", charset='utf8'
)
mycur = mycon.cursor()
mycur.execute("CREATE DATABASE IF NOT EXISTS HOSPITAL")
mycur.execute("USE HOSPITAL")

# Creating the PATIENT table if it doesn't exist


create_patient_table = """
CREATE TABLE IF NOT EXISTS PATIENT (
Pno INTEGER PRIMARY KEY,
Pname VARCHAR(50) NOT NULL,
dept VARCHAR(50) NOT NULL,
Age INTEGER NOT NULL,
Gender VARCHAR(10) ,
Diagnosis VARCHAR(100) NOT NULL,
Treatment VARCHAR(100) NOT NULL,

11
DateOfAdmission DATE NOT NULL,
DoctorName VARCHAR(50) NOT NULL,
PhoneNumber VARCHAR(15) NOT NULL
)
"""
mycur.execute(create_patient_table)

# Creating the DOCTOR table if it doesn't exist


create_doctor_table = """
CREATE TABLE IF NOT EXISTS DOCTOR (
SNo INTEGER PRIMARY KEY,
Name VARCHAR(50) NOT NULL,
Speciality VARCHAR(50) NOT NULL,
Gender VARCHAR(10) NOT NULL,
Experience INTEGER NOT NULL,
DateOfJoining DATE NOT NULL
)
"""
mycur.execute("drop table rooms")
create_room_table="""CREATE TABLE hospital.rooms (
RoomNumber INT PRIMARY KEY,
IsOccupied BOOLEAN DEFAULT FALSE )"""
mycur.execute(create_room_table)
mycur.execute('insert into rooms(roomnumber) values(101)')
mycur.execute('insert into rooms(roomnumber) values(102)')
mycur.execute('insert into rooms(roomnumber) values(103)')
mycur.execute('insert into rooms(roomnumber) values(104)')

12
mycur.execute('insert into rooms(roomnumber) values(105)')
# Define the colors and fonts
bg_color = "#f0f0f0"
button_color = "#4CAF50"
header_font = ("Arial", 20, "bold")
button_font = ("Arial", 12)
cr="""CREATE TABLE MEDICINE (
SNo INT AUTO_INCREMENT PRIMARY KEY,
Medicine VARCHAR(100) NOT NULL,
Manufacturer VARCHAR(100),
Quantity INT
)"""
mycur.execute(cr)

# Setting up Tkinter window


root = tk.Tk()
root.title("Hospital Management System")
tk.Label(root, text="Hospital management", font=header_font,
bg=bg_color).pack(pady=10)
root.geometry("400x400")

def manage_patient():
def insert_patient():
def submit():
13
try:
# Ensure database connection is active
if not mycon.is_connected():
raise mysql.connector.Error("Database connection lost.")

pno = int(entry_pno.get())
pname = entry_pname.get().strip()
dept = dept_combobox.get()
age = int(entry_age.get())
gender = gender_combobox.get() # Get the value from the combobox
diagnosis = entry_diagnosis.get().strip()
treatment = entry_treatment.get().strip()
date_of_admission = entry_date_of_admission.get().strip()
doctor_name = entry_doctor_name.get().strip()
phone_number = entry_phone_number.get().strip()

qry_check_doctor = "SELECT COUNT(*) FROM DOCTOR


WHERE Name=%s"
mycur.execute(qry_check_doctor, (doctor_name,))
doctor_exists = mycur.fetchone()[0]

if doctor_exists == 0:
messagebox.showerror("Error", f"Doctor '{doctor_name}' does not
exist.")
return

qry = """

14
INSERT INTO PATIENT (Pno, Pname, Dept, Age, Gender,
Diagnosis, Treatment, DateOfAdmission, DoctorName, PhoneNumber)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
"""
data = (pno, pname, dept, age, gender, diagnosis, treatment,
date_of_admission, doctor_name, phone_number)
mycur.execute(qry, data)

# Explicit commit after query execution


mycon.commit()
messagebox.showinfo("Success", "Record added successfully!")

# Close insert window and reopen Manage Patients window


insert_window.destroy()
except mysql.connector.IntegrityError as e:
if "1062" in str(e): # Error code 1062 refers to duplicate entry for a
primary key
messagebox.showerror("Error: ","patient id already exists!")
except mysql.connector.Error as err:
mycon.rollback() # Rollback in case of error
messagebox.showerror("error","incorrect value")
except ValueError:
messagebox.showerror("Error", "Invalid input! Please enter the
correct values.")
finally:
insert_window.destroy()

# Create window for patient insertion form


insert_window = tk.Toplevel(root)
15
insert_window.title("Insert Patient")
insert_window.configure(bg=bg_color)

tk.Label(insert_window, text="Insert Patient", font=header_font,


bg=bg_color).pack(pady=10)

# Create entry fields for patient details


tk.Label(insert_window, text="Patient Code:", bg=bg_color).pack(pady=5)
entry_pno = tk.Entry(insert_window)
entry_pno.pack(pady=5)

tk.Label(insert_window, text="Patient Name:",


bg=bg_color).pack(pady=5)
entry_pname = tk.Entry(insert_window)
entry_pname.pack(pady=5)

tk.Label(insert_window, text="blood group", bg=bg_color).pack(pady=5)


dept_combobox = ttk.Combobox(insert_window,values=["A+", "A-","
B+", "B-"," AB+", "AB-"," O+"," O-"])
dept_combobox.pack(pady=5)

tk.Label(insert_window, text="Age:", bg=bg_color).pack(pady=5)


entry_age = tk.Entry(insert_window)
entry_age.pack(pady=5)

tk.Label(insert_window, text="Gender:", bg=bg_color).pack(pady=5)


gender_combobox = ttk.Combobox(insert_window, values=["Male",
"Female", "Other"]) # Combobox for gender
gender_combobox.pack(pady=5) # Default value
16
tk.Label(insert_window, text="Diagnosis:", bg=bg_color).pack(pady=5)
entry_diagnosis = tk.Entry(insert_window)
entry_diagnosis.pack(pady=5)

tk.Label(insert_window, text="Treatment:", bg=bg_color).pack(pady=5)


entry_treatment = tk.Entry(insert_window)
entry_treatment.pack(pady=5)

tk.Label(insert_window, text="Date of Admission (YYYY-MM-DD):",


bg=bg_color).pack(pady=5)
entry_date_of_admission = tk.Entry(insert_window)
entry_date_of_admission.pack(pady=5)

tk.Label(insert_window, text="Doctor Name:",


bg=bg_color).pack(pady=5)
entry_doctor_name = tk.Entry(insert_window)
entry_doctor_name.pack(pady=5)

tk.Label(insert_window, text="Phone Number:",


bg=bg_color).pack(pady=5)
entry_phone_number = tk.Entry(insert_window)
entry_phone_number.pack(pady=5)

tk.Button(insert_window, text="Submit", command=submit,


font=button_font, bg=button_color, fg="white", width=15,
height=2).pack(pady=10)
tk.Button(insert_window, text="Cancel",
command=insert_window.destroy, font=button_font, bg="red", fg="white",
width=15, height=2).pack(pady=5)
17
# Ensure the database commits any pending transactions.
mycon.commit()

def update_patient():
def submit():
try:
pno = int(entry_pno.get())
pname = entry_pname.get().strip()
dept = dept_combobox.get()
age = int(entry_age.get())
gender = gender_combobox.get()
diagnosis = entry_diagnosis.get().strip()
treatment = entry_treatment.get().strip()
date_of_admission = entry_date_of_admission.get().strip()
doctor_name = entry_doctor_name.get().strip()
phone_number = entry_phone_number.get().strip()
qry_check_doctor = "SELECT COUNT(*) FROM DOCTOR
WHERE Name=%s"
mycur.execute(qry_check_doctor, (doctor_name,))
doctor_exists = mycur.fetchone()[0]

if doctor_exists == 0:
messagebox.showerror("Error", f"Doctor '{doctor_name}' does not
exist.")
return

18
qry = """
UPDATE PATIENT SET Pname=%s, Dept=%s, Age=%s,
Gender=%s, Diagnosis=%s, Treatment=%s, DateOfAdmission=%s,
DoctorName=%s, PhoneNumber=%s
WHERE Pno=%s
"""
data = (pname, dept, age, gender, diagnosis, treatment,
date_of_admission, doctor_name, phone_number, pno)
mycur.execute(qry, data)
mycon.commit()

if mycur.rowcount > 0:
messagebox.showinfo("Success", "Record updated successfully!")
else:
messagebox.showinfo("Info", "No record found with the given
Patient Code.")
except mysql.connector.Error as err:
mycon.rollback()
messagebox.showerror("Error", f"invalid entry")
except ValueError:
messagebox.showerror("Error", "Invalid input! Please enter the
correct values.")
update_window.destroy()

update_window = tk.Toplevel(root)
update_window.title("Update Patient")
update_window.configure(bg=bg_color)

19
tk.Label(update_window, text="Patient Code:",
bg=bg_color).pack(pady=5)
entry_pno = tk.Entry(update_window)
entry_pno.pack(pady=5)

tk.Label(update_window, text="Patient Name:",


bg=bg_color).pack(pady=5)
entry_pname = tk.Entry(update_window)
entry_pname.pack(pady=5)

tk.Label(update_window, text="blood group", bg=bg_color).pack(pady=5)


dept_combobox = ttk.Combobox(update_window,values=["A+"," A-",
"B+", "B-", "AB+"," AB-"," O+"," O-"])
dept_combobox.pack(pady=5)

tk.Label(update_window, text="Age:", bg=bg_color).pack(pady=5)


entry_age = tk.Entry(update_window)
entry_age.pack(pady=5)

tk.Label(update_window, text="Gender:", bg=bg_color).pack(pady=5)


gender_combobox = ttk.Combobox(update_window, values=["Male",
"Female", "Other"]) # Combobox for gender
gender_combobox.pack(pady=5)

tk.Label(update_window, text="Diagnosis:", bg=bg_color).pack(pady=5)


entry_diagnosis = tk.Entry(update_window)
entry_diagnosis.pack(pady=5)

tk.Label(update_window, text="Treatment:", bg=bg_color).pack(pady=5)


20
entry_treatment = tk.Entry(update_window)
entry_treatment.pack(pady=5)

tk.Label(update_window, text="Date of Admission (YYYY-MM-DD):",


bg=bg_color).pack(pady=5)
entry_date_of_admission = tk.Entry(update_window)
entry_date_of_admission.pack(pady=5)

tk.Label(update_window, text="Doctor Name:",


bg=bg_color).pack(pady=5)
entry_doctor_name = tk.Entry(update_window)
entry_doctor_name.pack(pady=5)

tk.Label(update_window, text="Phone Number:",


bg=bg_color).pack(pady=5)
entry_phone_number = tk.Entry(update_window)
entry_phone_number.pack(pady=5)

tk.Button(update_window, text="Submit", command=submit,


font=button_font, bg=button_color, fg="white", width=15,
height=2).pack(pady=10)
tk.Button(update_window, text="Cancel",
command=update_window.destroy, font=button_font, bg="red", fg="white",
width=15, height=2).pack(pady=5)

from datetime import datetime

def delete_patient():
def submit():
try:
21
pno = int(entry_pno.get())

# First, fetch the patient's details before deleting the record


qry_select = "SELECT Pname, DateOfAdmission, DoctorName,
Treatment FROM PATIENT WHERE Pno=%s"
mycur.execute(qry_select, (pno,))
patient = mycur.fetchone()

if patient:
pname, date_of_admission, doctor_name, treatment = patient

# Since `date_of_admission` is likely a `datetime.date` object, no need


for strptime
if isinstance(date_of_admission, datetime):
admission_date = date_of_admission.date()
else:
admission_date = date_of_admission # if it's already a date

# Delete the patient record


qry_delete = "DELETE FROM PATIENT WHERE Pno=%s"
mycur.execute(qry_delete, (pno,))
mycon.commit()

if mycur.rowcount > 0:
# Calculate bill amount (Example: $500 per day admitted)
discharge_date = datetime.now().date()
num_days = (discharge_date - admission_date).days
bill_amount = num_days * 1000 # Example: $1000 per day

22
# Print bill summary
bill_summary = f"""
--------- Hospital Bill ---------
Patient Name: {pname}
Doctor Name: {doctor_name}
Date of Admission: {admission_date}
Date of Discharge: {discharge_date}
Treatment Provided: {treatment}
Number of Days Admitted: {num_days}
Total Bill Amount: ${bill_amount}
---------------------------------
"""
# Print to console

# You can also show the bill in a message box


messagebox.showinfo("Discharge Summary", bill_summary)
else:
messagebox.showinfo("Info", "No record found")

else:
messagebox.showinfo("Info", "No patient found with the provided
Patient Code")

except mysql.connector.Error as err:


mycon.rollback()
messagebox.showerror("Error", f"Database error: {err}")
except ValueError:
23
messagebox.showerror("Error", "Invalid input! Please enter the correct
data type.")
delete_window.destroy()

delete_window = tk.Toplevel(root)
delete_window.title("Discharge Patient")
delete_window.configure(bg=bg_color)

tk.Label(delete_window, text="Patient Code:", bg=bg_color).pack(pady=10)


entry_pno = tk.Entry(delete_window)
entry_pno.pack(pady=5)

tk.Button(delete_window, text="Submit", command=submit,


font=button_font, bg=button_color, fg="white", width=15,
height=2).pack(pady=10)
tk.Button(delete_window, text="Cancel", command=delete_window.destroy,
font=button_font, bg="red", fg="white", width=15, height=2).pack(pady=5)
def display_patients():
display_window = tk.Toplevel(root)
display_window.title("view Patients")
display_window.configure(bg=bg_color)
display_window.geometry("800x400")

tk.Label(display_window, text="Patient Records", font=header_font,


bg=bg_color).pack(pady=10)

# Create a Treeview widget


columns = ["Pno", "Pname", "Dept", "Age", "Gender", "Diagnosis",
"Treatment", "DateOfAdmission", "DoctorName", "PhoneNumber"]

24
tree = ttk.Treeview(display_window, columns=columns, show="headings")

# Define column headings and width


for col in columns:
tree.heading(col, text=col)
tree.column(col, width=100, anchor="w")

# Fetch data from database


mycur.execute("SELECT * FROM PATIENT")
records = mycur.fetchall()

# Insert data into the Treeview


for record in records:
tree.insert("", tk.END, values=record)

tree.pack(expand=True, fill='both', padx=10, pady=10)

def sort_patients():
def sort_records():
sort_window = tk.Toplevel(root)
sort_window.title("Sort Patients")
sort_window.configure(bg=bg_color)
sort_window.geometry("400x400")

tk.Label(sort_window, text="Sort Patients By:", font=header_font,


bg=bg_color).pack(pady=10)

25
tk.Button(sort_window, text="Sort by Age", command=lambda:
sort_by('Age'), font=button_font, bg=button_color, fg="white", width=20,
height=2).pack(pady=5)
tk.Button(sort_window, text="Sort by Date of Admission",
command=lambda: sort_by('DateOfAdmission'), font=button_font,
bg=button_color, fg="white", width=20, height=2).pack(pady=5)

def sort_by(column_name):
mycur.execute(f"SELECT * FROM PATIENT ORDER BY
{column_name}")
records = mycur.fetchall()

display_window = tk.Toplevel(sort_window)
display_window.title(f"Patients Sorted by {column_name}")
display_window.configure(bg=bg_color)
display_window.geometry("800x400")

tk.Label(display_window, text=f"Patient Records Sorted by


{column_name}", font=header_font, bg=bg_color).pack(pady=10)

# Create a Treeview widget


columns = ["Pno", "Pname", "Dept", "Age", "Gender", "Diagnosis",
"Treatment", "DateOfAdmission", "DoctorName", "PhoneNumber"]
tree = ttk.Treeview(display_window, columns=columns,
show="headings")

# Define column headings and width


for col in columns:
tree.heading(col, text=col)
tree.column(col, width=100, anchor="w")

26
# Insert sorted data into the Treeview
for record in records:
tree.insert("", tk.END, values=record)

tree.pack(expand=True, fill='both', padx=10, pady=10)


sort_records()
def available_rooms():
def update_room_status(action, room_number):
try:
if action == "occupy":
# Check if the room is already occupied
qry_check = "SELECT IsOccupied FROM ROOMS WHERE
RoomNumber=%s"
mycur.execute(qry_check, (room_number,))
result = mycur.fetchone()

if result:
is_occupied = result[0]
if is_occupied:
messagebox.showinfo("Info", "Room is already occupied.")
return

# If room is not occupied, occupy it


qry_update = "UPDATE ROOMS SET IsOccupied=TRUE
WHERE RoomNumber=%s"
message = "Room occupied successfully!"
else:

27
messagebox.showinfo("Info", "Room does not exist.")
return

elif action == "unoccupy":


# Check if the room is already unoccupied
qry_check = "SELECT IsOccupied FROM ROOMS WHERE
RoomNumber=%s"
mycur.execute(qry_check, (room_number,))
result = mycur.fetchone()

if result:
is_occupied = result[0]
if not is_occupied:
messagebox.showinfo("Info", "Room is already unoccupied.")
return

# If room is occupied, unoccupy it


qry_update = "UPDATE ROOMS SET IsOccupied=FALSE
WHERE RoomNumber=%s"
message = "Room unoccupied successfully!"
else:
messagebox.showinfo("Info", "Room does not exist.")
return

mycur.execute(qry_update, (room_number,))
mycon.commit()

messagebox.showinfo("Success", message)

28
display_rooms() # Refresh the room list

except mysql.connector.Error as err:


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

def display_rooms():
display_window = tk.Toplevel(root)
display_window.title("Available Rooms")
display_window.configure(bg=bg_color)
display_window.geometry("600x400")

tk.Label(display_window, text="Available Rooms", font=header_font,


bg=bg_color).pack(pady=10)

# Create a Treeview widget


columns = ["RoomNumber", "Status"]
tree = ttk.Treeview(display_window, columns=columns, show="headings")

for col in columns:


tree.heading(col, text=col)
tree.column(col, width=150, anchor="w")

# Fetch available rooms from the database


qry = "SELECT RoomNumber, IsOccupied FROM ROOMS"
mycur.execute(qry)
rooms = mycur.fetchall()

29
# Insert data into the Treeview
for room in rooms:
room_number, is_occupied = room
status = "Occupied" if is_occupied else "Available"
tree.insert("", tk.END, values=(room_number, status))

tree.pack(expand=True, fill='both', padx=10, pady=10)

# Add buttons to occupy or unoccupy rooms


tk.Label(display_window, text="Room Number:",
bg=bg_color).pack(pady=5)
entry_room_number = tk.Entry(display_window)
entry_room_number.pack(pady=5)

tk.Button(display_window, text="Occupy Room", command=lambda:


update_room_status("occupy", int(entry_room_number.get())),
font=button_font, bg=button_color, fg="white", width=20,
height=2).pack(pady=10)
tk.Button(display_window, text="Unoccupy Room", command=lambda:
update_room_status("unoccupy", int(entry_room_number.get())),
font=button_font, bg=button_color, fg="white", width=20,
height=2).pack(pady=5)

display_rooms()

manage_window = tk.Toplevel(root)
manage_window.title("Manage Patients")
manage_window.geometry("800x400")
manage_window.configure(bg=bg_color)
30
tk.Label(manage_window, text="Manage Patients", font=header_font,
bg=bg_color).pack(pady=10)

tk.Button(manage_window, text="Admit Patient", command=insert_patient,


font=button_font, bg=button_color, fg="white", width=20,
height=2).pack(pady=5)
tk.Button(manage_window, text="Update Patient",
command=update_patient, font=button_font, bg=button_color, fg="white",
width=20, height=2).pack(pady=5)
tk.Button(manage_window, text="Discharge Patient",
command=delete_patient, font=button_font, bg=button_color, fg="white",
width=20, height=2).pack(pady=5)
tk.Button(manage_window, text="Display Patients",
command=display_patients, font=button_font, bg=button_color, fg="white",
width=20, height=2).pack(pady=5)
tk.Button(manage_window, text="Sort Patients", command=sort_patients,
font=button_font, bg=button_color, fg="white", width=20,
height=2).pack(pady=5)
tk.Button(manage_window, text="Rooms Available",
command=available_rooms, font=button_font, bg=button_color, fg="white",
width=20, height=2).pack(pady=5)

mycon.commit()
def manage_doctor():
# Create the manage window
manage_window = tk.Toplevel(root)
manage_window.title("Manage Doctors")
manage_window.geometry("800x400")
manage_window.configure(bg=bg_color)

31
def insert_doctor():
def submit():
try:
sno = int(entry_sno.get())
name = entry_name.get().strip()
speciality = entry_speciality.get().strip()
gender = gender_combobox.get()
experience = int(entry_experience.get())
date_of_joining = entry_date_of_joining.get().strip()

qry = """
INSERT INTO DOCTOR (SNo, Name, Speciality, Gender,
Experience, DateOfJoining)
VALUES (%s, %s, %s, %s, %s, %s)
"""
data = (sno, name, speciality, gender, experience, date_of_joining)
mycur.execute(qry, data)
mycon.commit()
messagebox.showinfo("Success", "Record added successfully!")
except mysql.connector.IntegrityError as e:
if "1062" in str(e): # Error code 1062 refers to duplicate entry for a
primary key
messagebox.showerror("Error:"," doctor id already exists!")
except mysql.connector.Error as err:
mycon.rollback() # Rollback in case of error
messagebox.showerror("error","incorrect value")
except ValueError:

32
messagebox.showerror("Error", "Invalid input! Please enter the
correct values.")
finally:
insert_window.destroy()

insert_window = tk.Toplevel(manage_window)
insert_window.title("Insert Doctor")
insert_window.configure(bg=bg_color)

tk.Label(insert_window, text="Insert Doctor", font=header_font,


bg=bg_color).pack(pady=10)

tk.Label(insert_window, text="Serial No:", bg=bg_color).pack(pady=5)


entry_sno = tk.Entry(insert_window)
entry_sno.pack(pady=5)

tk.Label(insert_window, text="Name:", bg=bg_color).pack(pady=5)


entry_name = tk.Entry(insert_window)
entry_name.pack(pady=5)

tk.Label(insert_window, text="Speciality:", bg=bg_color).pack(pady=5)


entry_speciality = tk.Entry(insert_window)
entry_speciality.pack(pady=5)

tk.Label(insert_window, text="Gender:", bg=bg_color).pack(pady=5)


gender_combobox = ttk.Combobox(insert_window, values=["Male",
"Female", "Other"]) # Combobox for gender
gender_combobox.pack(pady=5)

33
tk.Label(insert_window, text="Experience:", bg=bg_color).pack(pady=5)
entry_experience = tk.Entry(insert_window)
entry_experience.pack(pady=5)

tk.Label(insert_window, text="Date of Joining (YYYY-MM-DD):",


bg=bg_color).pack(pady=5)
entry_date_of_joining = tk.Entry(insert_window)
entry_date_of_joining.pack(pady=5)

tk.Button(insert_window, text="Submit", command=submit,


font=button_font, bg=button_color, fg="white", width=15,
height=2).pack(pady=10)
tk.Button(insert_window, text="Cancel",
command=insert_window.destroy, font=button_font, bg="red", fg="white",
width=15, height=2).pack(pady=5)

def sort_doctors():
def sort_records():
sort_window = tk.Toplevel(manage_window)
sort_window.title("Sort Doctors")
sort_window.configure(bg=bg_color)
sort_window.geometry("400x400")

tk.Label(sort_window, text="Sort Doctors By:", font=header_font,


bg=bg_color).pack(pady=10)

tk.Button(sort_window, text="Sort by Experience", command=lambda:


sort_by('Experience'), font=button_font, bg=button_color, fg="white",
width=20, height=2).pack(pady=5)

34
tk.Button(sort_window, text="Sort by Date of Joining",
command=lambda: sort_by('DateOfJoining'), font=button_font,
bg=button_color, fg="white", width=20, height=2).pack(pady=5)

def sort_by(column_name):
mycur.execute(f"SELECT * FROM DOCTOR ORDER BY
{column_name}")
records = mycur.fetchall()

display_window = tk.Toplevel(sort_window)
display_window.title(f"Doctors Sorted by {column_name}")
display_window.configure(bg=bg_color)
display_window.geometry("800x400")

tk.Label(display_window, text=f"Doctor Records Sorted by


{column_name}", font=header_font, bg=bg_color).pack(pady=10)

# Create a Treeview widget


columns = ["S.No", "Name", "Speciality", "Gender", "Experience",
"Date of Joining"]
tree = ttk.Treeview(display_window, columns=columns,
show="headings")

# Define column headings and width


for col in columns:
tree.heading(col, text=col)
tree.column(col, width=150, anchor="w")

# Insert sorted data into the Treeview

35
for record in records:
tree.insert("", tk.END, values=record)

tree.pack(expand=True, fill='both', padx=10, pady=10)

sort_records()

def update_doctor():
def submit():
try:
sno = int(entry_sno.get())
name = entry_name.get().strip()
speciality = entry_speciality.get().strip()
gender = gender_combobox.get()
experience = int(entry_experience.get())
date_of_joining = entry_date_of_joining.get().strip()

qry = """
UPDATE DOCTOR SET Name=%s, Speciality=%s, Gender=%s,
Experience=%s, DateOfJoining=%s
WHERE SNo=%s
"""
data = (name, speciality, gender, experience, date_of_joining, sno)
mycur.execute(qry, data)
mycon.commit()

if mycur.rowcount > 0:
messagebox.showinfo("Success", "Record updated successfully!")
36
else:
messagebox.showinfo("Info", "No record found with the given
Doctor Serial No.")
except mysql.connector.Error as err:
mycon.rollback()
messagebox.showerror("Error", f"invalid input")
except ValueError:
messagebox.showerror("Error", "Invalid input! Please enter the
correct values.")
update_window.destroy()

update_window = tk.Toplevel(manage_window)
update_window.title("Update Doctor")
update_window.configure(bg=bg_color)

tk.Label(update_window, text="Serial No:", bg=bg_color).pack(pady=5)


entry_sno = tk.Entry(update_window)
entry_sno.pack(pady=5)

tk.Label(update_window, text="Name:", bg=bg_color).pack(pady=5)


entry_name = tk.Entry(update_window)
entry_name.pack(pady=5)

tk.Label(update_window, text="Speciality:", bg=bg_color).pack(pady=5)


entry_speciality = tk.Entry(update_window)
entry_speciality.pack(pady=5)

tk.Label(update_window, text="Gender:", bg=bg_color).pack(pady=5)

37
gender_combobox = ttk.Combobox(update_window, values=["Male",
"Female", "Other"]) # Combobox for gender
gender_combobox.pack(pady=5)

tk.Label(update_window, text="Experience:", bg=bg_color).pack(pady=5)


entry_experience = tk.Entry(update_window)
entry_experience.pack(pady=5)

tk.Label(update_window, text="Date of Joining (YYYY-MM-DD):",


bg=bg_color).pack(pady=5)
entry_date_of_joining = tk.Entry(update_window)
entry_date_of_joining.pack(pady=5)

tk.Button(update_window, text="Submit", command=submit,


font=button_font, bg=button_color, fg="white", width=15,
height=2).pack(pady=10)
tk.Button(update_window, text="Cancel",
command=update_window.destroy, font=button_font, bg="red", fg="white",
width=15, height=2).pack(pady=5)

def delete_doctor():
def submit():
try:
sno = int(entry_sno.get())

qry = "DELETE FROM DOCTOR WHERE SNo=%s"


data = (sno,)
mycur.execute(qry, data)
mycon.commit()

38
if mycur.rowcount > 0:
messagebox.showinfo("Success", "Record deleted successfully!")
else:
messagebox.showinfo("Info", "No record found with the given
Serial No.")
except mysql.connector.Error as err:
mycon.rollback()
messagebox.showerror("Error", f"Database error: {err}")
except ValueError:
messagebox.showerror("Error", "Invalid input! Please enter the
correct data type.")
delete_window.destroy()

delete_window = tk.Toplevel(manage_window)
delete_window.title("Delete Doctor")
delete_window.configure(bg=bg_color)

tk.Label(delete_window, text="Serial No:", bg=bg_color).pack(pady=10)


entry_sno = tk.Entry(delete_window)
entry_sno.pack(pady=5)

tk.Button(delete_window, text="Submit", command=submit,


font=button_font, bg=button_color, fg="white", width=15,
height=2).pack(pady=10)
tk.Button(delete_window, text="Cancel",
command=delete_window.destroy, font=button_font, bg="red", fg="white",
width=15, height=2).pack(pady=5)

39
def display_doctors():
display_window = tk.Toplevel(manage_window)
display_window.title("Display Doctors")
display_window.configure(bg=bg_color)
display_window.geometry("800x400")

tk.Label(display_window, text="Doctor Records", font=header_font,


bg=bg_color).pack(pady=10)

# Create a Treeview widget


columns = ["S.No", "Name", "Speciality", "Gender", "Experience", "Date
of Joining"]
tree = ttk.Treeview(display_window, columns=columns, show="headings")

# Define column headings and width


for col in columns:
tree.heading(col, text=col)
tree.column(col, width=150, anchor="w")

# Fetch data from database


mycur.execute("SELECT * FROM DOCTOR")
records = mycur.fetchall()

# Insert data into the Treeview


for record in records:
tree.insert("", tk.END, values=record)

tree.pack(expand=True, fill='both', padx=10, pady=10)

40
tk.Label(manage_window, text="Manage Doctors", font=header_font,
bg=bg_color).pack(pady=10)
tk.Button(manage_window, text="Insert Doctor", command=insert_doctor,
font=button_font, bg=button_color, fg="white", width=20,
height=2).pack(pady=5)
tk.Button(manage_window, text="Display Doctors",
command=display_doctors, font=button_font, bg=button_color, fg="white",
width=20, height=2).pack(pady=5)
tk.Button(manage_window, text="Update Doctor", command=update_doctor,
font=button_font, bg=button_color, fg="white", width=20,
height=2).pack(pady=5)
tk.Button(manage_window, text="Delete Doctor", command=delete_doctor,
font=button_font, bg=button_color, fg="white", width=20,
height=2).pack(pady=5)
tk.Button(manage_window, text="Sort Doctors", command=sort_doctors,
font=button_font, bg=button_color, fg="white", width=20,
height=2).pack(pady=5)

def manage_medicine():
# Create the manage window
manage_window = tk.Toplevel(root)
manage_window.title("Manage Medicines")
manage_window.geometry("800x400")
manage_window.configure(bg=bg_color)

def insert_medicine():
def submit():
try:
sno = int(entry_sno.get())
medicine = entry_medicine.get().strip()
manufacturer = entry_manufacturer.get().strip()

41
quantity = int(entry_quantity.get())

qry = """
INSERT INTO MEDICINE (SNo, Medicine, Manufacturer, Quantity)
VALUES (%s, %s, %s, %s)
"""
data = (sno, medicine, manufacturer, quantity)
mycur.execute(qry, data)
mycon.commit()
messagebox.showinfo("Success", "Record added successfully!")
except mysql.connector.IntegrityError as e:
if "1062" in str(e): # Error code 1062 refers to duplicate entry for a
primary key
messagebox.showerror("Error: patient id already exists!")
except mysql.connector.Error as err:
mycon.rollback() # Rollback in case of error
messagebox.showerror("error","incorrect value")
except ValueError:
messagebox.showerror("Error", "Invalid input! Please enter the
correct values.")
finally:
insert_window.destroy()

insert_window = tk.Toplevel(manage_window)
insert_window.title("Insert Medicine")
insert_window.configure(bg=bg_color)
insert_window.geometry("400x300")

42
tk.Label(insert_window, text="Insert Medicine", font=header_font,
bg=bg_color).pack(pady=10)

tk.Label(insert_window, text="Serial No:", bg=bg_color).pack(pady=5)


entry_sno = tk.Entry(insert_window)
entry_sno.pack(pady=5)

tk.Label(insert_window, text="Medicine:", bg=bg_color).pack(pady=5)


entry_medicine = tk.Entry(insert_window)
entry_medicine.pack(pady=5)

tk.Label(insert_window, text="Manufacturer:",
bg=bg_color).pack(pady=5)
entry_manufacturer = tk.Entry(insert_window)
entry_manufacturer.pack(pady=5)

tk.Label(insert_window, text="Quantity:", bg=bg_color).pack(pady=5)


entry_quantity = tk.Entry(insert_window)
entry_quantity.pack(pady=5)

tk.Button(insert_window, text="Submit", command=submit,


font=button_font, bg=button_color, fg="white", width=15,
height=2).pack(pady=10)
tk.Button(insert_window, text="Cancel",
command=insert_window.destroy, font=button_font, bg="red", fg="white",
width=15, height=2).pack(pady=5)

def update_medicine():
def submit():

43
try:
sno = int(entry_sno.get())
medicine = entry_medicine.get().strip()
manufacturer = entry_manufacturer.get().strip()
quantity = int(entry_quantity.get())

qry = """
UPDATE MEDICINE SET Medicine=%s, Manufacturer=%s,
Quantity=%s
WHERE SNo=%s
"""
data = (medicine, manufacturer, quantity, sno)
mycur.execute(qry, data)
mycon.commit()

if mycur.rowcount > 0:
messagebox.showinfo("Success", "Record updated successfully!")
else:
messagebox.showinfo("Info", "No record found with the given
Serial No.")
except mysql.connector.Error as err:
mycon.rollback()
messagebox.showerror("Error", f"invalid input")
except ValueError:
messagebox.showerror("Error", "Invalid input! Please enter the
correct values.")
update_window.destroy()

44
update_window = tk.Toplevel(manage_window)
update_window.title("Update Medicine")
update_window.configure(bg=bg_color)
update_window.geometry("400x300")

tk.Label(update_window, text="Serial No:", bg=bg_color).pack(pady=5)


entry_sno = tk.Entry(update_window)
entry_sno.pack(pady=5)

tk.Label(update_window, text="Medicine:", bg=bg_color).pack(pady=5)


entry_medicine = tk.Entry(update_window)
entry_medicine.pack(pady=5)

tk.Label(update_window, text="Manufacturer:",
bg=bg_color).pack(pady=5)
entry_manufacturer = tk.Entry(update_window)
entry_manufacturer.pack(pady=5)

tk.Label(update_window, text="Quantity:", bg=bg_color).pack(pady=5)


entry_quantity = tk.Entry(update_window)
entry_quantity.pack(pady=5)

tk.Button(update_window, text="Submit", command=submit,


font=button_font, bg=button_color, fg="white", width=15,
height=2).pack(pady=10)
tk.Button(update_window, text="Cancel",
command=update_window.destroy, font=button_font, bg="red", fg="white",
width=15, height=2).pack(pady=5)

45
def delete_medicine():
def submit():
try:
sno = int(entry_sno.get())

qry = "DELETE FROM MEDICINE WHERE SNo=%s"


data = (sno,)
mycur.execute(qry, data)
mycon.commit()

if mycur.rowcount > 0:
messagebox.showinfo("Success", "Record deleted successfully!")
else:
messagebox.showinfo("Info", "No record found with the given
Serial No.")
except mysql.connector.Error as err:
mycon.rollback()
messagebox.showerror("Error", f"Database error: {err}")
except ValueError:
messagebox.showerror("Error", "Invalid input! Please enter the
correct data type.")
delete_window.destroy()

delete_window = tk.Toplevel(manage_window)
delete_window.title("Delete Medicine")
delete_window.configure(bg=bg_color)
delete_window.geometry("300x200")

46
tk.Label(delete_window, text="Serial No:", bg=bg_color).pack(pady=10)
entry_sno = tk.Entry(delete_window)
entry_sno.pack(pady=5)

tk.Button(delete_window, text="Submit", command=submit,


font=button_font, bg=button_color, fg="white", width=15,
height=2).pack(pady=10)
tk.Button(delete_window, text="Cancel",
command=delete_window.destroy, font=button_font, bg="red", fg="white",
width=15, height=2).pack(pady=5)

def display_medicines():
display_window = tk.Toplevel(manage_window)
display_window.title("Display Medicines")
display_window.configure(bg=bg_color)
display_window.geometry("800x400")

tk.Label(display_window, text="Medicine Records", font=header_font,


bg=bg_color).pack(pady=10)

# Create a Treeview widget


columns = ["S.No", "Medicine", "Manufacturer", "Quantity"]
tree = ttk.Treeview(display_window, columns=columns, show="headings")

# Define column headings and width


for col in columns:
tree.heading(col, text=col)
tree.column(col, width=150, anchor="w")

47
# Fetch data from database
mycur.execute("SELECT * FROM MEDICINE")
records = mycur.fetchall()

# Insert data into the Treeview


for record in records:
tree.insert("", tk.END, values=record)

tree.pack(expand=True, fill='both', padx=10, pady=10)

tk.Label(manage_window, text="Manage Medicines", font=header_font,


bg=bg_color).pack(pady=10)
tk.Button(manage_window, text="Insert Medicine",
command=insert_medicine, font=button_font, bg=button_color, fg="white",
width=20, height=2).pack(pady=5)
tk.Button(manage_window, text="Display Medicines",
command=display_medicines, font=button_font, bg=button_color, fg="white",
width=20, height=2).pack(pady=5)
tk.Button(manage_window, text="Update Medicine",
command=update_medicine, font=button_font, bg=button_color, fg="white",
width=20, height=2).pack(pady=5)
tk.Button(manage_window, text="Delete Medicine",
command=delete_medicine, font=button_font, bg=button_color, fg="white",
width=20, height=2).pack(pady=5)

# Main buttons
tk.Button(root, text="Manage Patients", command=manage_patient,
font=button_font, bg=button_color, fg="white", width=30,
height=2).pack(pady=10)

48
tk.Button(root, text="Manage Doctors", command=manage_doctor,
font=button_font, bg=button_color, fg="white", width=30,
height=2).pack(pady=10)
tk.Button(root, text="Manage medicine", command=manage_medicine,
font=button_font, bg=button_color, fg="white", width=30,
height=2).pack(pady=10)
mycon.commit()
root.mainloop()

49
SAMPLE OUTPUTS
1.MAIN MENU

2.MANAGE PATIENTS

50
3.MANAGE DOCTORS

4.MANAGE MEDICINE

51
TABLES
1.PATIENT

2.DOCTOR

3.MEDICINE

4.ROOMS

52
ERRORS
TYPE 1-PRIMARY KEY ALREADY EXISTS

TYPE 2-INCORRECT DATA TYPE

TYPE 3-IF NO ERROR

53
OUTPUTS
1.ADD

2.UPDATE

54
3.SORT

4.DISCHARGE

55
5.HOSPITAL BILL

6.OCCUPYING ROOMS

56
CONCLUSION

Security: The program could be made more secure by adding a


username and password clause.
Extra features: Extra features such as time of admission and
discharge could be added. There could have been an option for next of
kin. The doctor table could have more fields.
Web based project: An online web interface could be made that
would allow anyone to access the system from any device anywhere
in the hospital.

57
BIBLOGRAPHY

WIKIPEDIA
CHAT GPT
https://www.geeksforgeeks.org/python-gui-tkinter/

58

You might also like