Create a login form in Python with Tkinter

Python tkinter Basic: Exercise-16 with Solution

Write a Python program to create a Tkinter-based login form with input fields for userid and password.

Sample Solution:

Python Code:

import tkinter as tk
from tkinter import messagebox

# Function to validate the login
def validate_login():
    userid = username_entry.get()
    password = password_entry.get()

    # You can add your own validation logic here
    if userid == "admin" and password == "password":
        messagebox.showinfo("Login Successful", "Welcome, Admin!")
        messagebox.showerror("Login Failed", "Invalid username or password")

# Create the main window
parent = tk.Tk()
parent.title("Login Form")

# Create and place the username label and entry
username_label = tk.Label(parent, text="Userid:")

username_entry = tk.Entry(parent)

# Create and place the password label and entry
password_label = tk.Label(parent, text="Password:")

password_entry = tk.Entry(parent, show="*")  # Show asterisks for password

# Create and place the login button
login_button = tk.Button(parent, text="Login", command=validate_login)

# Start the Tkinter event loop


In the exercise above -

  • First we import the necessary modules from Tkinter.
  • The "validate_login()" function validates login credentials.
  • Next we create the main window with the title "Login Form."
  • Input fields for userid and password are created using tk.Entry widgets. The show="*" option for the password entry field displays asterisks.
  • A login button is created using tk.Button, and its command is set to the validate_login function.
  • The Tkinter event loop (root.mainloop()) keeps the GUI running and responsive to user interactions.

Sample Output:

Tkinter: Create a login form in Python with Tkinter. Part-1
Tkinter: Create a login form in Python with Tkinter. Part-2


Flowchart: Create a login form in Python with Tkinter.

Python Code Editor:

Previous: Create a temperature converter in Python using Tkinter.
Next: Create interactive tooltips in a Python Tkinter window.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.