I am new to Python and would like to implement a simple Employee Management System (as shown on the attached photo) that do the following functionality
• A GUI for entering, viewing, and exporting employee data. (Already completed)
• The ability to export data into an Excel or csv file. (Not done yet)
• The ability to import all data from an Excel or csv file into the GUI.
Here is an example of the GUI
And Here is the CSV File
Fullname Age Gender Position Phone Number Address
Ali Talib 59 Male Vice-Chancellor 1752555555 UK-London
Afaf Neamah 23 Female Manager 7912394404 UK-Plymouth
Hussein Neamah 22 Male Head of Department 7335952523 UK-London
Estabraq Aldalboos 33 Female Engineer 7575252324 UK-Plymouth
Nathan Clarke 45 Male Deputy Head of School 7916682090 UK-London
Neamah AL-Naffakh 37 Male Lecturer 7817792202 UK-Plymouth
I need to develop the code to do the following
• Validating Entry Widget (i.e., accepting valid input for each text box). For example, accept numbers only for Age, and mobile number and visa versa (i.e., doesnt accept number for name, gender, position)- Show message box for invalid input
Here is the code
import csv
from tkinter import *
from tkinter import messagebox
def load_data(path): # Load data from csv file at program start.
reader = csv.reader(open(path))
return list(reader)[1:]
window=Tk()
window.geometry("800x500 0 0")
window.title("Employee Management System")
window.maxsize(width=800,height=500)
window.minsize(width=800,height=500)
FILEPATH = '/Users/nhal-naffakh/Desktop/Desktop/Sec-Interview/Data.csv'
main_lst = load_data(FILEPATH) # Load csv data into `main_lst`
def view():
index = listbox1.curselection()[0]
NameLabel2.config(text=main_lst[index][0])
AgeLabel2.config(text=main_lst[index][1])
GenderLabel2.config(text=main_lst[index][2])
PositionLabel2.config(text=main_lst[index][3])
AddressLabel2.config(text=main_lst[index][4])
def OpenFile():
pass
def Add():
name = Nametxt.get() # get the name of new entry
lst = [name, Agetxt.get(), Gendertxt.get(), Positiontxt.get(), Numbertxt.get(), Addresstxt.get()]
main_lst.append(lst)
listbox1.insert(len(List_of_Name), name) # add it to the listbox list
List_of_Name.append(name) # store it in the list of names
messagebox.showinfo("Information","The data has been added successfully")
def Save():
with open(FILEPATH,"w") as file:
writer = csv.writer(file, lineterminator='\n')
writer.writerow(["Fullname","Age","Gender","Position","Phone Number","Address"])
writer.writerows(main_lst) # now when it writes to file it will contain all the data.
messagebox.showinfo("Information","Saved succesfully")
def Clear():
Nametxt.delete(0,END)
Agetxt.delete(0,END)
Gendertxt.delete(0,END)
Positiontxt.delete(0,END)
Numbertxt.delete(0,END)
Addresstxt.delete(0,END)
def Exit():
wayOut = messagebox.askyesno("Employee Management System", "Do you want to exit the system")
if wayOut > 0:
Save() # Added a call to save upon exiting.
window.destroy()
return
List_of_Name=[]
for x in list(range(0,len(main_lst))):
List_of_Name.append(main_lst[x][0])
var = StringVar(value=List_of_Name)
listbox1 = Listbox(window, listvariable=var)
listbox1.grid(row=3,column=0)
buttonView = Button(text="ViewRecord", padx=10, pady=4, bd=4,
font=('ariel',12,'bold'), width=8, fg='black',
bg="dark gray", command=view).grid(row=3,column=1)
NameLabel = Label(window,text="FullName").grid(row=5,column=0,sticky="w")
AgeLabel=Label(window,text="Age").grid(row=6,column=0,sticky="w")
GenderLabel=Label(window,text="Gender").grid(row=7,column=0,sticky="w")
PositionLabel=Label(window,text="Position").grid(row=8,column=0,sticky="w")
AddressLabel=Label(window,text="Address").grid(row=9,column=0,sticky="w")
NameLabel2=Label(window,text="")
NameLabel2.grid(row=5,column=1,sticky="w")
AgeLabel2=Label(window,text="")
AgeLabel2.grid(row=6,column=1,sticky="w")
GenderLabel2=Label(window,text="")
GenderLabel2.grid(row=7,column=1,sticky="w")
PositionLabel2=Label(window,text="")
PositionLabel2.grid(row=8,column=1,sticky="w")
AddressLabel2=Label(window,text="")
AddressLabel2.grid(row=9,column=1,sticky="w")
Namelabel3=Label(window,text="Full Name",
font=('arial',12,'bold'),bd=3,fg="white",
bg="dark blue",).grid(row=0,column=0,sticky="w")
Nametxt = Entry(window,font=('ariel',12),bd=4,width=22, justify='left')
Nametxt.grid(row=0,column=1)
Agelabel3=Label(window,text="Age",font=("ariel",12,'bold'),bd=3,fg='white',
bg="dark blue",).grid(row=0,column=2)
Agetxt=Entry(window,font=('ariel',12),bd=4, justify='left')
Agetxt.grid(row=0,column=3)
GenderLabel3=Label(window,text="Gender",font=('ariel',12,'bold'),bd=3,fg='white',
bg="dark blue").grid(row=1,column=0,sticky="w")
Gendertxt=Entry(window,font=('ariel',12),bd=4, justify='left')
Gendertxt.grid(row=1,column=1)
PositionLabel3=Label(window,text="Position",font=('ariel',12,'bold'),bd=3,fg='white',
bg="dark blue").grid(row=1,column=2,sticky="w")
Positiontxt=Entry(window,font=('ariel',12),bd=4, justify='left')
Positiontxt.grid(row=1,column=3)
NumberLabel3=Label(window,text="Mob Number",font=('ariel',12,'bold'),bd=3,fg='white',
bg="dark blue").grid(row=2,column=0,sticky="w")
Numbertxt=Entry(window,font=('ariel',12),bd=4, justify='left')
Numbertxt.grid(row=2,column=1)
AddressLabel3=Label(window,text="Address",font=('ariel',12,'bold'),bd=3,fg='white',
bg="dark blue").grid(row=2,column=2,sticky="w")
Addresstxt=Entry(window,font=('ariel',12),bd=4, justify='left')
Addresstxt.grid(row=2,column=3)
# Button
LoadButton=Button(text="Load File", padx=10, pady=4, bd=4, font=('ariel',12,'bold'),
width=8,fg='black',bg="dark gray", command=OpenFile).grid(row=3,column=2)
AddButton=Button(text="Add Record", padx=10, pady=4, bd=4, font=('ariel',12,'bold'),
width=8,fg='black',bg="dark gray",command=Add).grid(row=3,column=3)
SaveButton=Button(text="Save", padx=10, pady=4, bd=4, font=('ariel',12,'bold'),
width=8,fg='black',bg="dark gray",command=Save).grid(row=4,column=1)
ClearButton=Button(text="Clear", padx=10, pady=4, bd=4, font=('ariel',12,'bold'),
width=8,fg='black',bg="dark gray",command=Clear).grid(row=4,column=2)
ExitButton=Button(text="Exit", padx=10, pady=4, bd=4, font=('ariel',12,'bold'),
width=8,fg='black', bg="dark gray",command=Exit).grid(row=4,column=3)
window.mainloop()
CodePudding user response:
For validating the data You can place a text validation function with the Add Record
button callback, so that when the user clicks the add record it first checks each entry field to make sure that certain criteria are met.
For example, I added a validate_text function that is called on each entry widgets text when the add record button is clicked. It first makes sure the entry isn't left blank, then it checks for numbers only for the age and numbers field, and then checks the rest to make sure there are no numbers in the text. If any of the conditions are true then it shows an error messagebox and no record is added to the main_lst or the csv file. Otherwise it adds the record to the main_lst and to the gui.
import csv
from tkinter import *
from tkinter import messagebox
def load_data(path): # Load data from csv file at program start.
reader = csv.reader(open(path))
return list(reader)[1:]
window=Tk()
window.geometry("800x500 0 0")
window.title("Employee Management System")
window.maxsize(width=800,height=500)
window.minsize(width=800,height=500)
FILEPATH = 'data.csv'
main_lst = load_data(FILEPATH) # Load csv data into `main_lst`
def view():
index = listbox1.curselection()[0]
NameLabel2.config(text=main_lst[index][0])
AgeLabel2.config(text=main_lst[index][1])
GenderLabel2.config(text=main_lst[index][2])
PositionLabel2.config(text=main_lst[index][3])
AddressLabel2.config(text=main_lst[index][4])
def OpenFile():
pass
def validate_text(field, text):
if not text:
messagebox.showinfo("Invalid Entry","Values cannot be left blank.")
return False
elif field in ["number", "age"]:
if not text.isnumeric():
messagebox.showinfo("Invalid Entry", f"{field.title()} must be numeric.")
return False
elif not all([not i.isdigit() for i in text]):
messagebox.showinfo("Invalid Entry", f"Numbers not permitted in {field.title()} field.")
return False
return True
def Add():
entries = {"name": Nametxt, "age": Agetxt, "gender": Gendertxt, "position": Positiontxt, "number": Numbertxt,"address": Addresstxt}
values = []
for key, val in entries.items():
text = val.get()
if not validate_text(key, text):
return
values.append(text)
main_lst.append(values)
listbox1.insert(len(List_of_Name), values[0]) # add it to the listbox list
List_of_Name.append(values[0]) # store it in the list of names
messagebox.showinfo("Information","The data has been added successfully")
def Save():
with open(FILEPATH,"w") as file:
writer = csv.writer(file, lineterminator='\n')
writer.writerow(["Fullname","Age","Gender","Position","Phone Number","Address"])
writer.writerows(main_lst) # now when it writes to file it will contain all the data.
messagebox.showinfo("Information","Saved succesfully")
def Clear():
Nametxt.delete(0,END)
Agetxt.delete(0,END)
Gendertxt.delete(0,END)
Positiontxt.delete(0,END)
Numbertxt.delete(0,END)
Addresstxt.delete(0,END)
def Exit():
wayOut = messagebox.askyesno("Employee Management System", "Do you want to exit the system")
if wayOut > 0:
Save() # Added a call to save upon exiting.
window.destroy()
return
List_of_Name=[]
for x in list(range(0,len(main_lst))):
List_of_Name.append(main_lst[x][0])
var = StringVar(value=List_of_Name)
listbox1 = Listbox(window, listvariable=var)
listbox1.grid(row=3,column=0)
buttonView = Button(text="ViewRecord", padx=10, pady=4, bd=4,
font=('ariel',12,'bold'), width=8, fg='black',
bg="dark gray", command=view).grid(row=3,column=1)
NameLabel = Label(window,text="FullName").grid(row=5,column=0,sticky="w")
AgeLabel=Label(window,text="Age").grid(row=6,column=0,sticky="w")
GenderLabel=Label(window,text="Gender").grid(row=7,column=0,sticky="w")
PositionLabel=Label(window,text="Position").grid(row=8,column=0,sticky="w")
AddressLabel=Label(window,text="Address").grid(row=9,column=0,sticky="w")
NameLabel2=Label(window,text="")
NameLabel2.grid(row=5,column=1,sticky="w")
AgeLabel2=Label(window,text="")
AgeLabel2.grid(row=6,column=1,sticky="w")
GenderLabel2=Label(window,text="")
GenderLabel2.grid(row=7,column=1,sticky="w")
PositionLabel2=Label(window,text="")
PositionLabel2.grid(row=8,column=1,sticky="w")
AddressLabel2=Label(window,text="")
AddressLabel2.grid(row=9,column=1,sticky="w")
Namelabel3=Label(window,text="Full Name",
font=('arial',12,'bold'),bd=3,fg="white",
bg="dark blue",).grid(row=0,column=0,sticky="w")
Nametxt = Entry(window,font=('ariel',12),bd=4,width=22, justify='left')
Nametxt.grid(row=0,column=1)
Agelabel3=Label(window,text="Age",font=("ariel",12,'bold'),bd=3,fg='white',
bg="dark blue",).grid(row=0,column=2)
Agetxt=Entry(window,font=('ariel',12),bd=4, justify='left')
Agetxt.grid(row=0,column=3)
GenderLabel3=Label(window,text="Gender",font=('ariel',12,'bold'),bd=3,fg='white',
bg="dark blue").grid(row=1,column=0,sticky="w")
Gendertxt=Entry(window,font=('ariel',12),bd=4, justify='left')
Gendertxt.grid(row=1,column=1)
PositionLabel3=Label(window,text="Position",font=('ariel',12,'bold'),bd=3,fg='white',
bg="dark blue").grid(row=1,column=2,sticky="w")
Positiontxt=Entry(window,font=('ariel',12),bd=4, justify='left')
Positiontxt.grid(row=1,column=3)
NumberLabel3=Label(window,text="Mob Number",font=('ariel',12,'bold'),bd=3,fg='white',
bg="dark blue").grid(row=2,column=0,sticky="w")
Numbertxt=Entry(window,font=('ariel',12),bd=4, justify='left')
Numbertxt.grid(row=2,column=1)
AddressLabel3=Label(window,text="Address",font=('ariel',12,'bold'),bd=3,fg='white',
bg="dark blue").grid(row=2,column=2,sticky="w")
Addresstxt=Entry(window,font=('ariel',12),bd=4, justify='left')
Addresstxt.grid(row=2,column=3)
# Button
LoadButton=Button(text="Load File", padx=10, pady=4, bd=4, font=('ariel',12,'bold'),
width=8,fg='black',bg="dark gray", command=OpenFile).grid(row=3,column=2)
AddButton=Button(text="Add Record", padx=10, pady=4, bd=4, font=('ariel',12,'bold'),
width=8,fg='black',bg="dark gray",command=Add).grid(row=3,column=3)
SaveButton=Button(text="Save", padx=10, pady=4, bd=4, font=('ariel',12,'bold'),
width=8,fg='black',bg="dark gray",command=Save).grid(row=4,column=1)
ClearButton=Button(text="Clear", padx=10, pady=4, bd=4, font=('ariel',12,'bold'),
width=8,fg='black',bg="dark gray",command=Clear).grid(row=4,column=2)
ExitButton=Button(text="Exit", padx=10, pady=4, bd=4, font=('ariel',12,'bold'),
width=8,fg='black', bg="dark gray",command=Exit).grid(row=4,column=3)
window.mainloop()