from tkinter import *
import time
import pymysql
from tkinter import ttk, messagebox
import ttkthemes
Initialize global variables for slider functionality
text = ''
count = 0
def toplevel_data(title, button_text, command):
global idEntry, nameEntry, phoneEntry, emailEntry, addressEntry, genderEntry, dobEntry, screen
screen = Toplevel()
screen.title(title)
screen.grab_set()
screen.resizable(False, False)
idLabel = Label(screen, text='ID:', font=('times new roman', 20, 'bold'))
idLabel.grid(row=0, column=0, padx=30, pady=15, sticky=W)
idEntry = Entry(screen, font=('roman', 15, 'bold'), width=24)
idEntry.grid(row=0, column=1, pady=15, padx=10)
nameLabel = Label(screen, text='Name:', font=('times new roman', 20, 'bold'))
nameLabel.grid(row=1, column=0, padx=30, pady=15, sticky=W)
nameEntry = Entry(screen, font=('roman', 15, 'bold'), width=24)
nameEntry.grid(row=1, column=1, pady=15, padx=10)
phoneLabel = Label(screen, text='Mobile Number:', font=('times new roman', 20, 'bold'))
phoneLabel.grid(row=3, column=0, padx=30, pady=15, sticky=W)
phoneEntry = Entry(screen, font=('roman', 15, 'bold'), width=24)
phoneEntry.grid(row=3, column=1, pady=15, padx=10)
emailLabel = Label(screen, text='Email:', font=('times new roman', 20, 'bold'))
emailLabel.grid(row=4, column=0, padx=30, pady=15, sticky=W)
emailEntry = Entry(screen, font=('roman', 15, 'bold'), width=24)
emailEntry.grid(row=4, column=1, pady=15, padx=10)
addressLabel = Label(screen, text='Address:', font=('times new roman', 20, 'bold'))
addressLabel.grid(row=5, column=0, padx=30, pady=15, sticky=W)
addressEntry = Entry(screen, font=('roman', 15, 'bold'), width=24)
addressEntry.grid(row=5, column=1, pady=15, padx=10)
genderLabel = Label(screen, text='Gender:', font=('times new roman', 20, 'bold'))
genderLabel.grid(row=6, column=0, padx=30, pady=15, sticky=W)
genderEntry = Entry(screen, font=('roman', 15, 'bold'), width=24)
genderEntry.grid(row=6, column=1, pady=15, padx=10)
dobLabel = Label(screen, text='Date of Birth:', font=('times new roman', 20, 'bold'))
dobLabel.grid(row=7, column=0, padx=30, pady=15, sticky=W)
dobEntry = Entry(screen, font=('roman', 15, 'bold'), width=24)
dobEntry.grid(row=7, column=1, pady=15, padx=10)
user_button = ttk.Button(screen, text=button_text, command=command)
user_button.grid(row=8, columnspan=2, pady=15)
indexing = userTable.focus()
def update_data():
query='update student name=%s, mobile=%s, email=%s, address=%s, gender=%s, dob=%s, date=%s, time=%s where id=%s'
mycursor.execute(query, (nameEntry.get(), phoneEntry.get(), emailEntry.get(), addressEntry.get(), genderEntry.get(), dobEntry.get(), date, current_time, idEntry.get()))
con.commit()
messagebox.showinfo('Sucess', f'ID {idEntry.get()} is modified successfully', parent=screen)
screen.destroy()
show_user()
indexing = userTable.focus()
content=userTable.item(indexing)
listdata=content['values']
idEntry.insert(0, listdata[0])
nameEntry.insert(0, listdata[0])
phoneEntry.insert(0, listdata[2])
emailEntry.insert(0, listdata[3])
addressEntry.insert(0, listdata[4])
genderEntry.insert(0, listdata[5])
dobEntry.insert(0, listdata[6])
def show_user():
query = 'select *from user'
mycursor.execute(query)
fetched_data = mycursor.fetchall()
userTable.delete(*userTable.get_children())
for data in fetched_data:
userTable.insert('', END, values=data)
def delete_user():
indexing=userTable.focus()
print(indexing)
content=userTable.item(indexing)
content_id=content['values'][0]
query='delete *from user where id=%s'
mycursor.execute(query, content_id)
con.commit()
messagebox.showinfo('Deleted', f'ID {content_id} is deleted successfully')
query='select *from user'
mycursor.execute(query)
fetched_data=mycursor.fetchall()
userTable.delete(*userTable.get_children())
for data in fetched_data:
userTable.insert('', END, values=data)
def search_data():
query='select *from user where id=%s or name=%s or email=%s or mobile=%s or address=%s, gender=%s or dob=%s'
mycursor.execute(query, (idEntry.get(), nameEntry.get(), emailEntry.get(), phoneEntry.get(), addressEntry.get(), genderEntry.get(), dobEntry.get()))
userTable.delete(*userTable.get_children())
fetched_data=mycursor.fetchall()
for data in fetched_data:
userTable.insert('', END, values=data)
def add_data():
global con, mycursor # Declare these as global here to use the database connection
if idEntry.get()== '' or nameEntry.get()== '' or phoneEntry.get()== '' or emailEntry.get()== '' or addressEntry.get()== '' or genderEntry.get()== '' or dobEntry.get()== '':
messagebox.showerror('Error', 'All Fields are Required', parent=screen)
else:
try:
query = 'insert into user values (%s, %s, %s, %s, %s, %s, %s, %s)'
mycursor.execute(query, (idEntry.get(), nameEntry.get(), phoneEntry.get(), emailEntry.get(), addressEntry.get(),
genderEntry.get(), dobEntry.get(), date, current_time))
con.commit()
result = messagebox.askyesno('Confirm', 'Data Added Successfully. Do you want to clean the form?', parent= screen)
if result:
idEntry.delete(0, END)
nameEntry.delete(0, END)
phoneEntry.delete(0, END)
emailEntry.delete(0, END)
addressEntry.delete(0, END)
genderEntry.delete(0, END)
dobEntry.delete(0, END)
else:
pass
except:
messagebox.showerror('Error', 'ID cannot be repeated', parent = screen)
return
query='select *from user'
mycursor.execute(query)
fetched_data= mycursor.fetchall()
userTable.delete(*userTable.get_children())
for data in fetched_data:
datalist=list(data)
userTable.insert('', END, values=datalist)
Function to display the clock (date and time)
def clock():
global date, current_time
date = time.strftime('%d/%m/%Y')
current_time = time.strftime('%H:%M:%S')
datetimeLabel.config(text=f' Date: {date}\nTime: {current_time}')
datetimeLabel.after(1000, clock)
Function to create a scrolling effect for the title text
def slider():
global text, count
if count == len(s):
count = 0
text = ''
text = text + s[count]
sliderLabel.config(text=text)
count += 1
sliderLabel.after(300, slider)
Database connection and table creation functionality
def connect_database():
global mycursor, con # Declare them as global here
def connect():
host = hostEntry.get()
username = usernameEntry.get()
password = passwordEntry.get()
try:
con = pymysql.connect(host='localhost', user='root', password='marecris05')
mycursor = con.cursor()
# Check and create database if it doesn't exist
mycursor.execute("CREATE DATABASE IF NOT EXISTS ums")
mycursor.execute("USE ums")
# Create table if it doesn't exist
table_creation_query = """
CREATE TABLE IF NOT EXISTS user (
ID INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30),
phone VARCHAR(10),
email VARCHAR(30),
address VARCHAR(100),
gender VARCHAR(20),
dob VARCHAR(20),
date VARCHAR(50),
time VARCHAR(50)
)
"""
mycursor.execute(table_creation_query)
con.commit()
messagebox.showinfo('Success', 'Database Connection Successful', parent=connectWindow)
connectWindow.destroy()
# Enable buttons after successful connection
adduserButton.config(state=NORMAL)
searchuserButton.config(state=NORMAL)
updateuserButton.config(state=NORMAL)
showuserButton.config(state=NORMAL)
exportuserButton.config(state=NORMAL)
deleteuserButton.config(state=NORMAL)
except:
messagebox.showerror('Error', 'Invalid Details', parent=connectWindow)
try:
query = 'create database ums'
mycursor.execute(query)
query = 'use ums'
mycursor.execute(query)
query = 'create table user(ID int null primary key, name varchar(30), mobile varchar(10),email varchar(30),''address varchar(100),gender varchar(20), dob varchar(20),date varchar(50),time varchar(50))'
mycursor.execute(query)
except:
query = 'use ums'
mycursor.execute(query)
Database connection window
connectWindow = Toplevel()
connectWindow.grab_set()
connectWindow.geometry('470x250+730+230')
connectWindow.title('Database Connection')
connectWindow.resizable(0, 0)
hostnameLabel = Label(connectWindow, text='Host Name:', font=('arial', 20, 'bold'))
hostnameLabel.grid(row=0, column=0, padx=20)
hostEntry = Entry(connectWindow, font=('roman', 15, 'bold'), bd=2)
hostEntry.grid(row=0, column=1, padx=40, pady=20)
usernameLabel = Label(connectWindow, text='User Name:', font=('arial', 20, 'bold'))
usernameLabel.grid(row=1, column=0, padx=20)
usernameEntry = Entry(connectWindow, font=('roman', 15, 'bold'), bd=2)
usernameEntry.grid(row=1, column=1, padx=40, pady=20)
passwordLabel = Label(connectWindow, text='Password:', font=('arial', 20, 'bold'))
passwordLabel.grid(row=2, column=0, padx=20)
passwordEntry = Entry(connectWindow, font=('roman', 15, 'bold'), bd=2)
passwordEntry.grid(row=2, column=1, padx=40, pady=20)
connectButton = ttk.Button(connectWindow, text='CONNECT', command=connect)
connectButton.grid(row=3, columnspan=2)
Main GUI Code
root = ttkthemes.ThemedTk()
root.get_themes()
root.set_theme('radiance')
root.geometry('1174x680+0+0')
root.resizable(0, 0)
root.title('User Management System')
Display current date and time
datetimeLabel = Label(root, font=('times new roman', 18, 'bold'))
datetimeLabel.place(x=5, y=5)
clock()
Scrolling text for the system title
s = 'User Management System'
sliderLabel = Label(root, text=s, font=('arial', 28, 'italic bold'), width=30)
sliderLabel.place(x=200, y=0)
slider()
Connect to database button
connectButton = ttk.Button(root, text='Connect Database', command=connect_database)
connectButton.place(x=980, y=0)
Left Panel (Navigation)
leftFrame = Frame(root)
leftFrame.place(x=50, y=80, width=300, height=600)
logo_image = PhotoImage(file='person.png')
logo_Label = Label(leftFrame, image=logo_image)
logo_Label.grid(row=0, column=0)
adduserButton = ttk.Button(leftFrame, text='Add User', width=25, state=DISABLED, command=lambda :toplevel_data('Add User', 'Add', add_data))
adduserButton.grid(row=1, column=0, pady=20)
searchuserButton = ttk.Button(leftFrame, text='Search User', width=25, state=DISABLED, command=lambda :toplevel_data('Search User', 'Search', search_data))
searchuserButton.grid(row=2, column=0, pady=20)
deleteuserButton = ttk.Button(leftFrame, text='Delete User', width=25, state=DISABLED, command=delete_user)
deleteuserButton.grid(row=3, column=0, pady=20)
updateuserButton = ttk.Button(leftFrame, text='Update User', width=25, state=DISABLED, command=lambda :toplevel_data('Update User', 'Update', update_data))
updateuserButton.grid(row=4, column=0, pady=20)
showuserButton = ttk.Button(leftFrame, text='Show User', width=25, state=DISABLED, command=show_user)
showuserButton.grid(row=5, column=0, pady=20)
exportuserButton = ttk.Button(leftFrame, text='Export Data', width=25, state=DISABLED)
exportuserButton.grid(row=6, column=0, pady=20)
exitButton = ttk.Button(leftFrame, text='Exit', width=25)
exitButton.grid(row=7, column=0, pady=20)
Right Panel (User Table)
rightFrame = Frame(root)
rightFrame.place(x=350, y=80, width=820, height=600)
scrollBarX = Scrollbar(rightFrame, orient=HORIZONTAL)
scrollBarY = Scrollbar(rightFrame, orient=VERTICAL)
userTable = ttk.Treeview(rightFrame, columns=('ID', 'Name', 'Mobile Number', 'Email', 'Address', 'Gender',
'Date of Birth', 'Added Date', 'Added Time'),
xscrollcommand=scrollBarX.set, yscrollcommand=scrollBarY.set)
scrollBarX.pack(side=BOTTOM, fill=X)
scrollBarY.pack(side=RIGHT, fill=Y)
scrollBarX.config(command=userTable.xview)
scrollBarY.config(command=userTable.yview)
userTable.heading('ID', text='ID')
userTable.heading('Name', text='Name')
userTable.heading('Mobile Number', text='Mobile')
userTable.heading('Email', text='Email')
userTable.heading('Address', text='Address')
userTable.heading('Gender', text='Gender')
userTable.heading('Date of Birth', text='DOB')
userTable.heading('Added Date', text='Date')
userTable.heading('Added Time', text='Time')
userTable.column('ID', width=50, anchor=CENTER)
userTable.column('Name', width=300, anchor=CENTER)
userTable.column('Email', width=300, anchor=CENTER)
userTable.column('Mobile Number', width=200, anchor=CENTER)
userTable.column('Address', width=300, anchor=CENTER)
userTable.column('Gender', width=100, anchor=CENTER)
userTable.column('Date of Birth', width=100, anchor=CENTER)
userTable.column('Added Date', width=200, anchor=CENTER)
userTable.column('Added Time', width=200, anchor=CENTER)
style=ttk.Style()
style.configure('Treeview', rowheight=40, font=('arial', 15, 'bold'))
userTable['show'] = 'headings'
userTable.pack(fill=BOTH, expand=True)
root.mainloop()
error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\PC\PycharmProjects\PythonUMS\ums.py", line 224, in connect
mycursor.execute(query)
^^^^^^^^
UnboundLocalError: cannot access local variable 'mycursor' where it is not associated with a value
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Program Files\Python313\Lib\tkinter_init.py", line 2068, in _call
return self.func(*args)
~~~~~^^^^^^^
File "C:\Users\PC\PycharmProjects\PythonUMS\ums.py", line 231, in connect
mycursor.execute(query)
^^^^^^^^
UnboundLocalError: cannot access local variable 'mycursor' where it is not associated with a value
Top comments (0)