Creating a Login And Registration Form in Python

In this tutorial we will create a Login And Registration Form using Python. Python is a widely used advanced-level programming language for a general technique to the developer. Beginners find Python a clean syntax and indentation structure-based, and it is easy to learn because of its less semicolon problem. So let do the coding.

Getting started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Installing SQLite Browser

After you installed Python, we will now then install the SQLite, here's the link for the DB Browser for SQLite http://sqlitebrowser.org/. Then open the SQLite and create a database naming "db_member".

Importing Modules

After setting up the installation and the database, run the IDLE and click the file and then new file. After that a new window will appear with an emty file this will be the text editor for the python.

Then copy the code that I provided below and paste it inside the IDLE text editor.

  1. from tkinter import *
  2. import tkinter.messagebox as tkMessageBox
  3. import sqlite3

Setting up the Main Frame

After importing the modules, we will now then create the mainframe for the application. To do that just copy the code below and paste it inside the IDLE text editor.

  1. root = Tk()
  2. root.title("Python: Simple Inventory System")
  3.  
  4. width = 640
  5. height = 480
  6. screen_width = root.winfo_screenwidth()
  7. screen_height = root.winfo_screenheight()
  8. x = (screen_width/2) - (width/2)
  9. y = (screen_height/2) - (height/2)
  10. root.geometry("%dx%d+%d+%d" % (width, height, x, y))
  11. root.resizable(0, 0)

Creating the Database Connection

Then after setting up the design we will now create the database function. To do that just simply copy the code below and paste it inside the IDLE text editor.

  1. def Database():
  2. global conn, cursor
  3. conn = sqlite3.connect("db_member.db")
  4. cursor = conn.cursor()
  5. cursor.execute("CREATE TABLE IF NOT EXISTS `member` (mem_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, username TEXT, password TEXT, firstname TEXT, lastname TEXT)")

Assigning Variables

This is where the we will assign the variables. This code will assign each of the variables to be use later in the application.

  1. #=======================================VARIABLES=====================================
  2. USERNAME = StringVar()
  3. PASSWORD = StringVar()
  4. FIRSTNAME = StringVar()
  5. LASTNAME = StringVar()

Designing the Layout

After creating the Main Frame we will now add some layout to the application. Just kindly copy the code below and paste it inside the IDLE text editor.

  1. def LoginForm():
  2. global LoginFrame, lbl_result1
  3. LoginFrame = Frame(root)
  4. LoginFrame.pack(side=TOP, pady=80)
  5. lbl_username = Label(LoginFrame, text="Username:", font=('arial', 25), bd=18)
  6. lbl_username.grid(row=1)
  7. lbl_password = Label(LoginFrame, text="Password:", font=('arial', 25), bd=18)
  8. lbl_password.grid(row=2)
  9. lbl_result1 = Label(LoginFrame, text="", font=('arial', 18))
  10. lbl_result1.grid(row=3, columnspan=2)
  11. username = Entry(LoginFrame, font=('arial', 20), textvariable=USERNAME, width=15)
  12. username.grid(row=1, column=1)
  13. password = Entry(LoginFrame, font=('arial', 20), textvariable=PASSWORD, width=15, show="*")
  14. password.grid(row=2, column=1)
  15. btn_login = Button(LoginFrame, text="Login", font=('arial', 18), width=35, command=Login)
  16. btn_login.grid(row=4, columnspan=2, pady=20)
  17. lbl_register = Label(LoginFrame, text="Register", fg="Blue", font=('arial', 12))
  18. lbl_register.grid(row=0, sticky=W)
  19. lbl_register.bind('<Button-1>', ToggleToRegister)
  20.  
  21. def RegisterForm():
  22. global RegisterFrame, lbl_result2
  23. RegisterFrame = Frame(root)
  24. RegisterFrame.pack(side=TOP, pady=40)
  25. lbl_username = Label(RegisterFrame, text="Username:", font=('arial', 18), bd=18)
  26. lbl_username.grid(row=1)
  27. lbl_password = Label(RegisterFrame, text="Password:", font=('arial', 18), bd=18)
  28. lbl_password.grid(row=2)
  29. lbl_firstname = Label(RegisterFrame, text="Firstname:", font=('arial', 18), bd=18)
  30. lbl_firstname.grid(row=3)
  31. lbl_lastname = Label(RegisterFrame, text="Lastname:", font=('arial', 18), bd=18)
  32. lbl_lastname.grid(row=4)
  33. lbl_result2 = Label(RegisterFrame, text="", font=('arial', 18))
  34. lbl_result2.grid(row=5, columnspan=2)
  35. username = Entry(RegisterFrame, font=('arial', 20), textvariable=USERNAME, width=15)
  36. username.grid(row=1, column=1)
  37. password = Entry(RegisterFrame, font=('arial', 20), textvariable=PASSWORD, width=15, show="*")
  38. password.grid(row=2, column=1)
  39. firstname = Entry(RegisterFrame, font=('arial', 20), textvariable=FIRSTNAME, width=15)
  40. firstname.grid(row=3, column=1)
  41. lastname = Entry(RegisterFrame, font=('arial', 20), textvariable=LASTNAME, width=15)
  42. lastname.grid(row=4, column=1)
  43. btn_login = Button(RegisterFrame, text="Register", font=('arial', 18), width=35, command=Register)
  44. btn_login.grid(row=6, columnspan=2, pady=20)
  45. lbl_login = Label(RegisterFrame, text="Login", fg="Blue", font=('arial', 12))
  46. lbl_login.grid(row=0, sticky=W)
  47. lbl_login.bind('<Button-1>', ToggleToLogin)

Creating the Main Function

This is where the code that contains the main funcitions. This code will register the user and can login after creating an account. To do that just copy and write these blocks of code.

  1. #=======================================METHODS=======================================
  2. def Exit():
  3. result = tkMessageBox.askquestion('System', 'Are you sure you want to exit?', icon="warning")
  4. if result == 'yes':
  5. root.destroy()
  6. exit()
  7.  
  8. def ToggleToLogin(event=None):
  9. RegisterFrame.destroy()
  10. LoginForm()
  11.  
  12. def ToggleToRegister(event=None):
  13. LoginFrame.destroy()
  14. RegisterForm()
  15.  
  16. def Register():
  17. Database()
  18. if USERNAME.get == "" or PASSWORD.get() == "" or FIRSTNAME.get() == "" or LASTNAME.get == "":
  19. lbl_result2.config(text="Please complete the required field!", fg="orange")
  20. else:
  21. cursor.execute("SELECT * FROM `member` WHERE `username` = ?", (USERNAME.get(),))
  22. if cursor.fetchone() is not None:
  23. lbl_result2.config(text="Username is already taken", fg="red")
  24. else:
  25. cursor.execute("INSERT INTO `member` (username, password, firstname, lastname) VALUES(?, ?, ?, ?)", (str(USERNAME.get()), str(PASSWORD.get()), str(FIRSTNAME.get()), str(LASTNAME.get())))
  26. conn.commit()
  27. USERNAME.set("")
  28. PASSWORD.set("")
  29. FIRSTNAME.set("")
  30. LASTNAME.set("")
  31. lbl_result2.config(text="Successfully Created!", fg="black")
  32. cursor.close()
  33. conn.close()
  34. def Login():
  35. Database()
  36. if USERNAME.get == "" or PASSWORD.get() == "":
  37. lbl_result1.config(text="Please complete the required field!", fg="orange")
  38. else:
  39. cursor.execute("SELECT * FROM `member` WHERE `username` = ? and `password` = ?", (USERNAME.get(), PASSWORD.get()))
  40. if cursor.fetchone() is not None:
  41. lbl_result1.config(text="You Successfully Login", fg="blue")
  42. else:
  43. lbl_result1.config(text="Invalid Username or password", fg="red")
  44. LoginForm()

Additional Layout

The code below is for creating an exit action in menu bar.

  1. #========================================MENUBAR WIDGETS==================================
  2. menubar = Menu(root)
  3. filemenu = Menu(menubar, tearoff=0)
  4. filemenu.add_command(label="Exit", command=Exit)
  5. menubar.add_cascade(label="File", menu=filemenu)
  6. root.config(menu=menubar)

Initializing the Application

After finishing the function save the application as index.py. This function will run the code and check if the main is initialize properly. To do that copy the code below and paste it inside the IDLE text editor.

  1. #========================================INITIALIZATION===================================
  2. if __name__ == '__main__':
  3. root.mainloop()

There you have it we just created a Login And Registration Form Using Python. I hope that this simple tutorial help you for what you are looking for. For more updates and tutorials just kindly visit this site.

Enjoy Coding!!

Comments

Submitted bySambat (not verified)on Sat, 07/28/2018 - 19:18

Please provide some more python sample code like this. It is hard to find python sample code. Big thanks
Submitted byDaniaref (not verified)on Mon, 06/13/2022 - 01:06

Всем привет !

Add new comment