Python Login And Register Form With MySQL

How to Create Login and Register Form in Python Tkinter with MySQL Database

Python Login And Register Form With MySQL


In this Python Long Tutorial we will go step by step on How To Design a Login Form And a Register Form, plus how to make a basic main form / dashboard to show to the user after 
successfully logging.

What We Are Gonna Use In This Project:

- Python Programming Language.
- Tkinter for Graphical User interfaces.
- VsCode Editor.
- MySQL Database.
- PhpMyAdmin.


What We Will Do In This Project:


- Design Two Forms For The Login and Signup Using Frames.
- Create Close Button To Close The Form.
- Connect Python To MySQL Database, To Add The Registred User Data In The Signup Form or to Check If The User Exist In The Login Form.
- Browse and Select Image From Your Computer and Set The File Path In a Label .
- Check If The User Leave Some Fields Empty.
- Check If The User Enter Username That Already Exists.
- Check If The User Enter a Wrong Password In The Confirmation Field.   




Project Source Code:

import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter.ttk import *
from tkinter import filedialog
from tkinter import messagebox
import mysql.connector
from py_mainform import mainform

root = Tk()
connection = mysql.connector.connect(host='localhost', user='root', port='3306',
password='', database='py_lg_rg_db')
c = connection.cursor()

# width and height
w = 450
h = 525
# background color
bgcolor = "#bdc3c7"

# ----------- CENTER FORM ------------- #
root.overrideredirect(1) # remove border
ws = root.winfo_screenwidth()
hs = root.winfo_screenheight()
x = (ws-w)/2
y = (hs-h)/2
root.geometry("%dx%d+%d+%d" % (w, h, x, y))

# ----------- HEADER ------------- #

headerframe = tk.Frame(root, highlightbackgroun='yellow', highlightcolor='yellow',
highlightthickness=2, bg='#95a5a6', width=w, height=70)
titleframe = tk.Frame(headerframe, bg='yellow', padx=1, pady=1)
title_label = tk.Label(titleframe, text='Register', padx=20, pady=5, bg='green',
fg='#fff', font=('Tahoma',24), width=8)
close_button = tk.Button(headerframe, text='x', borderwidth=1, relief='solid',
font=('Verdana',12))

headerframe.pack()
titleframe.pack()
title_label.pack()
close_button.pack()

titleframe.place(y=26, relx=0.5, anchor=CENTER)
close_button.place(x=410, y=10)

# close window
def close_win():
root.destroy()

close_button['command'] = close_win

# ----------- END HEADER ------------- #

mainframe = tk.Frame(root, width=w, height=h)

# ----------- Login Page ------------- #
loginframe = tk.Frame(mainframe, width=w, height=h)
login_contentframe = tk.Frame(loginframe, padx=30, pady=100,
highlightbackgroun='yellow', highlightcolor='yellow',
highlightthickness=2, bg=bgcolor)

username_label = tk.Label(login_contentframe, text='Username:',
font=('Verdana',16), bg=bgcolor)
password_label = tk.Label(login_contentframe, text='Password:',
font=('Verdana',16), bg=bgcolor)

username_entry = tk.Entry(login_contentframe, font=('Verdana',16))
password_entry = tk.Entry(login_contentframe, font=('Verdana',16), show='*')

login_button = tk.Button(login_contentframe,text="Login", font=('Verdana',16),
bg='#2980b9',fg='#fff', padx=25, pady=10, width=25)

go_register_label = tk.Label(login_contentframe,
text=">> don't have an account? create one" ,
font=('Verdana',10), bg=bgcolor, fg='red')

mainframe.pack(fill='both', expand=1)
loginframe.pack(fill='both', expand=1)
login_contentframe.pack(fill='both', expand=1)

username_label.grid(row=0, column=0, pady=10)
username_entry.grid(row=0, column=1)

password_label.grid(row=1, column=0, pady=10)
password_entry.grid(row=1, column=1)

login_button.grid(row=2, column=0, columnspan=2, pady=40)

go_register_label.grid(row=3, column=0, columnspan=2, pady=20)

# create a function to display the register frame
def go_to_register():
loginframe.forget()
registerframe.pack(fill="both", expand=1)
title_label['text'] = 'Register'
title_label['bg'] = '#27ae60'


go_register_label.bind("<Button-1>", lambda page: go_to_register())


# create a function to make the user login
def login():
username = username_entry.get().strip()
password = password_entry.get().strip()
vals = (username, password,)
select_query = "SELECT * FROM `users` WHERE `username` = %s and `password` = %s"
c.execute(select_query, vals)
user = c.fetchone()
if user is not None:
#messagebox.showinfo('Test','Test')
mainformwindow = tk.Toplevel()
app = mainform(mainformwindow)
root.withdraw() # hide the root
mainformwindow.protocol("WM_DELETE_WINDOW", close_win) # close the app

else:
messagebox.showwarning('Error','wrong username or password')



login_button['command'] = login


# ----------- Register Page ------------- #

registerframe = tk.Frame(mainframe, width=w, height=h)
register_contentframe = tk.Frame(registerframe, padx=15, pady=15,
highlightbackgroun='yellow', highlightcolor='yellow',
highlightthickness=2, bg=bgcolor)

fullname_label_rg = tk.Label(register_contentframe, text='Fullname:',
font=('Verdana',14), bg=bgcolor)
username_label_rg = tk.Label(register_contentframe, text='Username:',
font=('Verdana',14), bg=bgcolor)
password_label_rg = tk.Label(register_contentframe, text='Password:',
font=('Verdana',14), bg=bgcolor)
confirmpass_label_rg = tk.Label(register_contentframe, text='Re-Password:',
font=('Verdana',14), bg=bgcolor)
phone_label_rg = tk.Label(register_contentframe, text='Phone:',
font=('Verdana',14), bg=bgcolor)
gender_label_rg = tk.Label(register_contentframe, text='Gender:',
font=('Verdana',14), bg=bgcolor)
image_label_rg = tk.Label(register_contentframe, text='Profile Pic:',
font=('Verdana',14), bg=bgcolor)



fullname_entry_rg = tk.Entry(register_contentframe, font=('Verdana',14), width=22)
username_entry_rg = tk.Entry(register_contentframe, font=('Verdana',14), width=22)
password_entry_rg = tk.Entry(register_contentframe, font=('Verdana',14), width=22,
show='*')
confirmpass_entry_rg = tk.Entry(register_contentframe, font=('Verdana',14), width=22,
show='*')
phone_entry_rg = tk.Entry(register_contentframe, font=('Verdana',14), width=22)

radiosframe = tk.Frame(register_contentframe)
gender = StringVar()
gender.set('Male')
male_radiobutton = tk.Radiobutton(radiosframe, text='Male', font=('Verdana',14),
bg=bgcolor, variable=gender, value='Male')
female_radiobutton = tk.Radiobutton(radiosframe, text='Female', font=('Verdana',14),
bg=bgcolor, variable=gender, value='Female')

selectimage_frame = tk.Frame(register_contentframe, bg=bgcolor)
selectimage_button = tk.Button(selectimage_frame, text='select image', bg='#fff')
imagepath_label_rg = tk.Label(selectimage_frame, text='image path...', bg=bgcolor,
width=22)


register_button = tk.Button(register_contentframe,text="Register", font=('Verdana',16)
, bg='#2980b9',fg='#fff', padx=25, pady=10, width=25)

go_login_label = tk.Label(register_contentframe,
text=">> already have an account? sign in" ,
font=('Verdana',10), bg=bgcolor, fg='red')

#mainframe.pack(fill='both', expand=1)
#registerframe.pack(fill='both', expand=1)
register_contentframe.pack(fill='both', expand=1)

fullname_label_rg.grid(row=0, column=0, pady=5, sticky='e')
fullname_entry_rg.grid(row=0, column=1)

username_label_rg.grid(row=1, column=0, pady=5, sticky='e')
username_entry_rg.grid(row=1, column=1)

password_label_rg.grid(row=2, column=0, pady=5, sticky='e')
password_entry_rg.grid(row=2, column=1)

confirmpass_label_rg.grid(row=3, column=0, pady=5, sticky='e')
confirmpass_entry_rg.grid(row=3, column=1)

phone_label_rg.grid(row=4, column=0, pady=5, sticky='e')
phone_entry_rg.grid(row=4, column=1)

gender_label_rg.grid(row=5, column=0, pady=5, sticky='e')
radiosframe.grid(row=5, column=1)
male_radiobutton.grid(row=0, column=0)
female_radiobutton.grid(row=0, column=1)

image_label_rg.grid(row=6, column=0, pady=5, sticky='e')
selectimage_frame.grid(row=6, column=1)
selectimage_button.grid(row=0, column=0, padx=10, pady=10)
imagepath_label_rg.grid(row=0, column=1)


register_button.grid(row=7, column=0, columnspan=2, pady=20)

go_login_label.grid(row=8, column=0, columnspan=2, pady=10)


# create a function to select image
def select_image():
filename = filedialog.askopenfilename(initialdir='/images',
title="Select Profile Picture",
filetypes=(("png images","*.png"),("jpg images","*.jpg")))
imagepath_label_rg['text'] = filename

selectimage_button['command'] = select_image
# --------------------------------------- #


# create a function to display the login frame
def go_to_login():
registerframe.forget()
loginframe.pack(fill="both", expand=1)
title_label['text'] = 'Login'
title_label['bg'] = '#2980b9'


go_login_label.bind("<Button-1>", lambda page: go_to_login())
# --------------------------------------- #

# create a function to check if the username already exists
def check_username(username):
username = username_entry_rg.get().strip()
vals = (username,)
select_query = "SELECT * FROM `users` WHERE `username` = %s"
c.execute(select_query, vals)
user = c.fetchone()
if user is not None:
return True
else:
return False



# --------------------------------------- #


# create a function to register a new user
def register():

fullname = fullname_entry_rg.get().strip() # remove white space
username = username_entry_rg.get().strip()
password = password_entry_rg.get().strip()
confirm_password = confirmpass_entry_rg.get().strip()
phone = phone_entry_rg.get().strip()
gdr = gender.get()
imgpath = imagepath_label_rg['text']

if len(fullname) > 0 and len(username) > 0 and len(password) > 0
and len(phone) > 0:
if check_username(username) == False:
if password == confirm_password:
vals = (fullname, username, password, phone, gdr, imgpath)
insert_query = "INSERT INTO `users`(`fullname`, `username`, `password`
, `phone`, `gender`, `image_path`) VALUES
(%s,%s,%s,%s,%s,%s)"
c.execute(insert_query, vals)
connection.commit()
messagebox.showinfo('Register','your account has been created
successfully')
else:
messagebox.showwarning('Password','incorrect password confirmation')
else:
messagebox.showwarning('Duplicate Username','This Username Already Exists,
try another one')
else:
messagebox.showwarning('Empty Fields','make sure to enter all the information')

register_button['command'] = register

# --------------------------------------- #

# ------------------------------------------------------------------------ #


root.mainloop()



# main form
import tkinter as tk
from tkinter import *

w = 1200
h = 650

class mainform:
def __init__(self, master):
self.master = master
# ----------- CENTER FORM ------------- #
ws = self.master.winfo_screenwidth()
hs = self.master.winfo_screenheight()
x = (ws-w)/2
y = (hs-h)/2
self.master.geometry("%dx%d+%d+%d" % (w, h, x, y))

# ----------- MENU ------------- #

self.frame = tk.Frame(self.master)
self.menubar = Menu(self.frame)
self.products = Menu(self.menubar)
self.products.add_command(label="Add")
self.products.add_command(label="Edit")
self.products.add_command(label="Remove")

self.menubar.add_cascade(menu=self.products, label="Product")

self.categories = Menu(self.menubar)
self.categories.add_command(label="Add")
self.categories.add_command(label="Edit")
self.categories.add_command(label="Remove")

self.menubar.add_cascade(menu=self.categories, label="Category")

self.frame.pack()

# ------------------------------ #

self.master.config(menu=self.menubar, bg="#ecf0f1")
self.lbl = tk.Label(self.master, text='Main Form', font=('verdana',50, 'bold')
, fg='#2A2C2B',bg="#ecf0f1")
self.lbl.place(rely=0.5, relx=0.5, anchor=CENTER)



The Final Result:

python login form design using tkinter
The Login Form

design register form using python tkinter
If The Username Or The Password Does Not Exist

python tkinter register form design
The Register/Signup Form

python signup form design in tkinter
If The User Left On Field Or More Empty

register form in python and mysql
If The User Select a Username That Already Exist

python tkinter dashboard form
the main form / dashboard



if you want the source code click on the download button below


download the source code








Python - Login Form With MySQL DataBase

How To Make SignIn Form In Python Using Tkinter With MySQL DataBase

Python - Login Form With MySQL DataBase

In this Python Tutorial we will see Make A Login Form Using Python Tkinter And MySQL Database.



Source Code:

- Create the Login Form


#login form
import tkinter as tk
from tkinter import messagebox
from py_mainform_2 import mainform
import mysql.connector

# connect with mysql database
connection = mysql.connector.connect(
host='localhost',
user='root',
password='',
port='3306',
database='py_lg_rg_db'
)

c = connection.cursor()

root = tk.Tk()

# create a function to close the window
def close_window():
root.destroy()

# width and height
w = 400
h = 260

class loginForm:
def __init__(self,master):
self.master = master
# start center window
ws = self.master.winfo_screenwidth()
hs = self.master.winfo_screenheight()
x = (ws-w)/2
y = (hs-h)/2
self.master.geometry('%dx%d+%d+%d' % (w, h, x, y))
# end center window

# start create widgets
self.frame = tk.Frame(self.master, bg='#fff')
self.btnsFrame = tk.Frame(self.frame, bg='#fff', padx=40, pady=15)
self.windowTitle = tk.Label(self.frame, text='Login Window', bg='#fff',
fg='blue', font=('Tahoma',20), pady=30)
self.usernameLabel = tk.Label(self.frame, text='Username:', bg='#fff',
font=('Verdana',16))
self.usernameTextbox = tk.Entry(self.frame, font=('Verdana',12), width=25,
borderwidth='2', relief='ridge')
self.passwordLabel = tk.Label(self.frame, text='Password:', bg='#fff',
font=('Verdana',16))
self.passwordTextbox = tk.Entry(self.frame,show='*', font=('Verdana',12),
width=25, borderwidth='2', relief='ridge')
self.btnLogin = tk.Button(self.btnsFrame, text='Login', bg='green',
font=('Verdana',12), fg='#fff', padx=25,
pady=10, command=self.login_func)
self.btnCancel = tk.Button(self.btnsFrame, text='Cancel', bg='orange',
font=('Verdana',12), fg='#fff', padx=25,
pady=10, command=close_window)
# end create widgets

# start place widgets
self.frame.pack(fill='both')
self.windowTitle.grid(row=0, column=0, columnspan=2)
self.usernameLabel.grid(row=1, column=0)
self.usernameTextbox.grid(row=1, column=1)
self.passwordLabel.grid(row=2, column=0, pady=(10,0))
self.passwordTextbox.grid(row=2, column=1, pady=(10,0))
self.btnsFrame.grid(row=3, column=0, columnspan=2, pady=10)
self.btnLogin.grid(row=0, column=0, padx=(0,35))
self.btnCancel.grid(row=0, column=1)
# end place widgets

# create a function to login
def login_func(self):
username = self.usernameTextbox.get()
password = self.passwordTextbox.get()
select_query = 'SELECT * FROM `users` WHERE `username` = %s and password = %s'
vals = (username, password,)
c.execute(select_query, vals)
#print(c.fetchall())
user = c.fetchone()
if user is not None:
#messagebox.showinfo('Login', 'Yes')
mainformwindow = tk.Toplevel()
app = mainform(mainformwindow)
root.withdraw()
mainformwindow.protocol('WM_DELETE_WINDOW', close_window)
else:
messagebox.showwarning('Error', 'Enter a Valid Username & Password')



def main():
login_window = loginForm(root)
root.mainloop()

if __name__ == '__main__':
main()

- Create the Mainform

# main form
import tkinter as tk
from tkinter import *

w = 1200
h = 650

class mainform:
def __init__(self, master):
self.master = master
# ----------- CENTER FORM ------------- #
ws = self.master.winfo_screenwidth()
hs = self.master.winfo_screenheight()
x = (ws-w)/2
y = (hs-h)/2
self.master.geometry("%dx%d+%d+%d" % (w, h, x, y))


self.frame = tk.Frame(self.master)
self.frame.pack()

self.master.config(bg="#2A2C2B")
self.lbl = tk.Label(self.master, text='Main Form', font=('verdana',50, 'bold')
, fg='#ecf0f1',bg="#2A2C2B")
self.lbl.place(rely=0.5, relx=0.5, anchor=CENTER)

OUTPUT:

Python Login Form With MySQL DataBase

Python Login Form With MySQL DataBase Using Tkinter

Python Login Form With MySQL DataBase In Tkinter

Main Form


if you want the source code click on the download button below

download the source code








Connect Python to MySQL Database

How to Connect Python to MySQL Database and Display Data

Connect Python to MySQL Database

In This Python Tutorial We Will See How To Connect Python To MySQL DataBase Using PIP in VsCode.








Source Code:


import mysql.connector

connection = mysql.connector.connect(
host='localhost',
user='root',
password='',
port='3306',
database='test_py'
)

c = connection.cursor()

select_query = 'SELECT * FROM `users_2`'
c.execute(select_query)
data = c.fetchall()

# display data
for row in data:
print(row)


OUTPUT:

How to Connect Python to MySQL Database and Display Data







C# Library Management System Source Code

Create a Library Management System (LMS) Project Using C# And MySQL Database

C# Library Management System Source Code

in this c# complete project tutorial serie we will see how to create a library management system using windowForm in csharp programming language and mysql database.

goals of this project:
- give students / curious persons an example so they can learn from it.
- helping people create their first project. 
- sharing knowledge with others.

tools:
- c# programming language.
- microsoft visual studio express 2013.
- mysql database.
- phpmyadmin.
- xampp server.
- pixabay.com ( website to get free images ).
- canva.com ( to create the book covers )

Watch This Full Demo



1 - The Login & Dashboard Form

the login form will allow the Users to login into the library system application Dashboard Form.


C# Library Management System Source Code - Login Form

the login and the dashboard forms will be displayed at the same time.
the dashboard form will be disabled until the user login successfully.


C# Library Management System Source Code - Dashboard Form

if the user is a simple user, he can't access to the circulation and the users section.


C# Library Management System Source Code - Dashboard Form

if the user is an admin, he can't access the users section.


C# Library Management System Source Code - Dashboard Form

if the user is an owner.


C# Library Management System Source Code - Dashboard Form

and as you can see the dashboard form consist of 3 parts:
1 - show some data analytics.

C# Library Management System Source Code - Analytics

2 - show a menu in the left-side.

C# Library Management System Source Code - Left Side

3 - show the latest books in the bottom.
C# Library Management System Source Code - Latest Books

2 - The Library System - Genres Form

- this form allow the users to add, edit remove books genre, and display all the genres in a datagridview.

C# Library Management System Source Code - Genres


3 - The Library System - Manage Authors


here the user can add a new author to the system. view all authors in a datagridview. edit, remove the selected one from the datagridview.

C# Library Management System Source Code - Authors

- if you want to see a selected author books, just select one from the datagridview and click the "Show Author Books" button.

C# Library Management System Source Code - Author Books


- you can also export the authors data to a text file by clicking the "Export Authors To Txt File" button.

C# Library Management System Source Code - Export Authors


4 - The Library System - Manage Books


this form is where you can manage the library members.
this form has a menu in the left side where you can choose the action you want to perform.

when this form show up it will display the add book panel.

C# Library Management System Source Code - Add Book

if you want to edit a book, just click on the edit button and the edit panel will be displayed.

C# Library Management System Source Code - Edit Book

you can see all the books by clicking on the "Books List" button.

C# Library Management System Source Code - Books List

in this panel you can select a book and delete it or editing it.

C# Library Management System Source Code - Edit Book

and to delete a book > click the "Delete" button and enter the book id.

C# Library Management System Source Code - Remove Book

and just like the manage authors form, here you can also export data ( books ) to a text file.

C# Library Management System Source Code - Export Book


5 - The Library System - Manage Members


in this form you can:
- add a new member to the system.
- edit the selected  member from the datagridview.
- delete the selected  member from the datagridview.


C# Library Management System Source Code - Members

6 - The Library System - Circulation Form

ISSUE BOOK: in this panel you can issue a book to a specific member for a specific date.


C# Library Management System Source Code - Circulation

to select a book enter the book id and click "search book".
if this book id exist you will see the book title under the book id field. 
if this book is available ( by counting the quantity and other stuff  ) you will see YES if not you will see NO
the same is for the member, enter the member id > click search > you will see the member full name
C# Library Management System Source Code - Circulation


C# Library Management System Source Code - Circulation

when you click on the book title, an info card will show up.

C# Library Management System Source Code - Info Card

the same for the member, when you click on the member full name, an info card will show up.


C# Library Management System Source Code - Info Card

RETURN BOOK: in this panel you can return a book or set it to lost.
and you can see data in the datagridview all or depending on the status.


C# Library Management System Source Code - Circulation

7 - The Library System - Manage Users Form

in this form you can manage the users.
this form contains:
1 - table with all users:
2 - a button to add a new user.
3 - a button to edit the selected user.
4 - a button to remove the selected user.


C# Library Management System Source Code - Users




if you want the source code click on the download button below