Skip to main content

Simple Login Application in Python Tutorial with Source Code

Screenshot
Body

In this tutorial, we will create a Simple Login Application in Python. Python has a design philosophy that emphasizes code readability. That's why Python is very easy to use especially for beginners who just started programming. It is very easy to learn the syntax emphasizes readability and it can reduce time-consuming in developing. So let's now 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/.

Importing Modules

After setting up the installation and the database, run the IDLE and click file and then new file. After that a new window will appear containing a black 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 sqlite3

Setting up the Main Frame

After importing the modules, we will now then create the main frame 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 Login Application")
  3. width = 400
  4. height = 280
  5. screen_width = root.winfo_screenwidth()
  6. screen_height = root.winfo_screenheight()
  7. x = (screen_width/2) - (width/2)
  8. y = (screen_height/2) - (height/2)
  9. root.geometry("%dx%d+%d+%d" % (width, height, x, y))
  10. root.resizable(0, 0)

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. #==============================VARIABLES======================================
  2. USERNAME = StringVar()
  3. PASSWORD = StringVar()
  4.  
  5. #==============================FRAMES=========================================
  6. Top = Frame(root, bd=2, relief=RIDGE)
  7. Top.pack(side=TOP, fill=X)
  8. Form = Frame(root, height=200)
  9. Form.pack(side=TOP, pady=20)
  10.  
  11. #==============================LABELS=========================================
  12. lbl_title = Label(Top, text = "Python: Simple Login Application", font=('arial', 15))
  13. lbl_title.pack(fill=X)
  14. lbl_username = Label(Form, text = "Username:", font=('arial', 14), bd=15)
  15. lbl_username.grid(row=0, sticky="e")
  16. lbl_password = Label(Form, text = "Password:", font=('arial', 14), bd=15)
  17. lbl_password.grid(row=1, sticky="e")
  18. lbl_text = Label(Form)
  19. lbl_text.grid(row=2, columnspan=2)
  20.  
  21. #==============================ENTRY WIDGETS==================================
  22. username = Entry(Form, textvariable=USERNAME, font=(14))
  23. username.grid(row=0, column=1)
  24. password = Entry(Form, textvariable=PASSWORD, show="*", font=(14))
  25. password.grid(row=1, column=1)
  26.  
  27. #==============================BUTTON WIDGETS=================================
  28. btn_login = Button(Form, text="Login", width=45, command=Login)
  29. btn_login.grid(pady=25, row=3, columnspan=2)
  30. btn_login.bind('<Return>', Login)

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. #==============================METHODS========================================
  2. def Database():
  3. global conn, cursor
  4. conn = sqlite3.connect("pythontut.db")
  5. cursor = conn.cursor()
  6. cursor.execute("CREATE TABLE IF NOT EXISTS `member` (mem_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, username TEXT, password TEXT)")
  7. cursor.execute("SELECT * FROM `member` WHERE `username` = 'admin' AND `password` = 'admin'")
  8. if cursor.fetchone() is None:
  9. cursor.execute("INSERT INTO `member` (username, password) VALUES('admin', 'admin')")
  10. conn.commit()

Creating the Main Function

This is the main function where the Entry will be check if there is a user exist in the database, after login correctly a new window will pop up. To do that just simply copy the code below then paste it inside the IDLE text editor.

  1. def Login(event=None):
  2. Database()
  3. if USERNAME.get() == "" or PASSWORD.get() == "":
  4. lbl_text.config(text="Please complete the required field!", fg="red")
  5. else:
  6. cursor.execute("SELECT * FROM `member` WHERE `username` = ? AND `password` = ?", (USERNAME.get(), PASSWORD.get()))
  7. if cursor.fetchone() is not None:
  8. HomeWindow()
  9. USERNAME.set("")
  10. PASSWORD.set("")
  11. lbl_text.config(text="")
  12. else:
  13. lbl_text.config(text="Invalid username or password", fg="red")
  14. USERNAME.set("")
  15. PASSWORD.set("")
  16. cursor.close()
  17. conn.close()
  18.  
  19. def HomeWindow():
  20. global Home
  21. root.withdraw()
  22. Home = Toplevel()
  23. Home.title("Python: Simple Login Application")
  24. width = 600
  25. height = 500
  26. screen_width = root.winfo_screenwidth()
  27. screen_height = root.winfo_screenheight()
  28. x = (screen_width/2) - (width/2)
  29. y = (screen_height/2) - (height/2)
  30. root.resizable(0, 0)
  31. Home.geometry("%dx%d+%d+%d" % (width, height, x, y))
  32. lbl_home = Label(Home, text="Successfully Login!", font=('times new roman', 20)).pack()
  33. btn_back = Button(Home, text='Back', command=Back).pack(pady=20, fill=X)
  34.  
  35. def Back():
  36. Home.destroy()
  37. root.deiconify()

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. #==============================INITIALIATION==================================
  2. if __name__ == '__main__':
  3. root.mainloop()

There you have it we just created a Simple Login Application using Python. I hope that this simple tutorial helps you expand the idea of Python programming. For more updates and tutorials just kindly visit this site.

Enjoy Coding!!

Invalid Credentail Image

invalid credential

Valid Credentail Image

valid credential

Demo

Looking for Free Python Projects? Visit the link below.

Free Python Projects with Source Code

Comments

Submitted bykff (not verified)on Wed, 06/14/2017 - 09:56

it help me a lot.
Submitted bytman540 (not verified)on Tue, 04/10/2018 - 20:28

In reply to by Gerome823 (not verified)

It is undefined probably because you defined "Login" after the command was binded to the button. Move the "def Login():" above the bind command
Submitted bypudsss (not verified)on Sat, 07/07/2018 - 19:01

in the database connection stage i made a elif statement to save the values employee def Database(): global conn, cursor conn = sqlite3.connect("SCCSDatabase.db") cursor = conn.cursor() cursor.execute("CREATE TABLE IF NOT EXISTS `member` (mem_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, username TEXT, password TEXT)") cursor.execute("CREATE TABLE IF NOT EXISTS `employee` (employee_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, username1 TEXT, password1 TEXT)") cursor.execute("SELECT * FROM `member` WHERE `username` = 'admin' AND `password` = 'admin'") cursor.execute("SELECT * FROM `employee` WHERE `username1` = 'employee' AND `password1` = 'employee'") if cursor.fetchone() is None: cursor.execute("INSERT INTO `member` (username, password) VALUES('admin', 'admin')") conn.commit() elif cursor.fetchone() is None: cursor.execute("INSERT INTO `employee` (username1, password1) VALUES('employee', 'employee')") conn.commit() can you help me create another login with those values
Submitted byanonymouson Mon, 03/02/2020 - 01:02

  1. from turtle import*
  2. pensize(3)
  3. clr=("blue","brown","red","green","orange","purple")
  4. for i in clr:
  5. right(60)
  6. color(i)
  7. circle(90)
Submitted byAfumba (not verified)on Tue, 08/25/2020 - 15:24

This tutorial is very informative and readable and clearly understood to every levels.

Add new comment