Home » A Python program that generates a random password

A Python program that generates a random password

by pqzrmred71

Here’s a Python program that generates a random password based on user-selected criteria using tkinter.

The user can select the length of the password and whether it should include numbers, letters, and special characters.

Code

import tkinter as tk
from tkinter import messagebox
import random
import string

# Function to generate a random password
def generate_password():
    try:
        length = int(length_entry.get())
        if length < 1:
            raise ValueError("Password length must be greater than zero.")
    except ValueError:
        messagebox.showerror("Invalid Input", "Please enter a valid length.")
        return

    # Determine character set based on checkboxes
    character_set = ""
    if letters_var.get():
        character_set += string.ascii_letters
    if numbers_var.get():
        character_set += string.digits
    if special_chars_var.get():
        character_set += string.punctuation

    if not character_set:
        messagebox.showwarning("Selection Error", "Please select at least one character type.")
        return

    # Generate password
    password = ''.join(random.choice(character_set) for _ in range(length))
    password_display.config(text=password)

# Initialize the main window
root = tk.Tk()
root.title("Random Password Generator")
root.geometry("400x300")

# Title Label
title_label = tk.Label(root, text="Random Password Generator", font=("Helvetica", 16))
title_label.pack(pady=10)

# Length selection
tk.Label(root, text="Password Length:").pack()
length_entry = tk.Entry(root)
length_entry.pack(pady=5)

# Checkboxes for character types
letters_var = tk.BooleanVar()
numbers_var = tk.BooleanVar()
special_chars_var = tk.BooleanVar()

letters_check = tk.Checkbutton(root, text="Include Letters (A-Z, a-z)", variable=letters_var)
letters_check.pack()

numbers_check = tk.Checkbutton(root, text="Include Numbers (0-9)", variable=numbers_var)
numbers_check.pack()

special_chars_check = tk.Checkbutton(root, text="Include Special Characters (!@#$...)", variable=special_chars_var)
special_chars_check.pack()

# Generate Button
generate_button = tk.Button(root, text="Generate Password", command=generate_password)
generate_button.pack(pady=10)

# Password Display Label
password_display = tk.Label(root, text="", font=("Helvetica", 14), fg="blue")
password_display.pack(pady=10)

# Run the main loop
root.mainloop()

Explanation

  1. Import Required Libraries:
    • tkinter: Used to create the GUI components for the application.
    • messagebox from tkinter: Used to display error messages and warnings.
    • random: Used to generate random characters for the password.
    • string: Provides character sets for letters, digits, and punctuation.
  2. generate_password Function:
    • This function is called when the user clicks the “Generate Password” button.
    • Get the Length of Password:
      • length = int(length_entry.get()): Retrieves the desired length from the entry field and converts it to an integer.
      • If the input is invalid or less than 1, an error message is displayed using messagebox.showerror.
    • Determine Character Set:
      • character_set is initialized as an empty string.
      • If letters_var.get() is True, string.ascii_letters (A-Z, a-z) is added to character_set.
      • If numbers_var.get() is True, string.digits (0-9) is added to character_set.
      • If special_chars_var.get() is True, string.punctuation (special characters) is added to character_set.
      • If no character type is selected, a warning message is displayed with messagebox.showwarning.
    • Generate the Password:
      • password = ”.join(random.choice(character_set) for _ in range(length)): Generates a password of the specified length by randomly selecting characters from character_set.
      • password_display.config(text=password): Updates the display label to show the generated password.
  3. Initialize the Main Application Window:
    • root = tk.Tk(): Creates the main application window.
    • root.title(“Random Password Generator”): Sets the title of the window.
    • root.geometry(“400×300”): Sets the window size to 400×300 pixels.
  4. Title Label:
    • title_label = tk.Label(…): Displays the title “Random Password Generator” at the top of the window.
  5. Length Entry:
    • length_entry = tk.Entry(root): An entry widget where the user enters the desired password length.
  6. Character Type Checkboxes:
    • letters_var, numbers_var, and special_chars_var are BooleanVar variables to hold the state (checked/unchecked) of each checkbox.
    • Checkbutton(root, text=”…”, variable=letters_var): Creates checkboxes for letters, numbers, and special characters, each linked to a respective BooleanVar.
  7. Generate Button:
    • generate_button = tk.Button(…): Creates a button labeled “Generate Password”.
    • command=generate_password: Specifies that generate_password should be called when the button is clicked.
  8. Password Display Label:
    • password_display = tk.Label(…): Displays the generated password.
    • Initially, it’s set to an empty string, but it updates with the generated password after clicking “Generate Password”.
  9. Run the Main Event Loop:
    • root.mainloop() starts the main loop, keeping the application window open and responsive to user actions.

Usage

  1. Open the Application:
    • The user opens the application and sees options to set the password length and checkboxes for including letters, numbers, and special characters.
  2. Select Password Options:
    • The user enters a desired length (e.g., 12) and selects one or more character types by checking the corresponding boxes.
  3. Generate Password:
    • When the user clicks “Generate Password”, a random password is generated based on the selected criteria and displayed in the GUI.

Output

If the user selects:

  • Length: 12
  • Character Types: Letters, Numbers, Special Characters

The output might look like:

Password: T8$j2@bL!vQw

Notes

  • Error Handling:
    • Checks for valid length input and character type selection to avoid errors or empty passwords.
  • Customization:
    • You can easily modify the code to include or exclude other character types (e.g., uppercase-only or lowercase-only letters).
  • Security:
    • This generator uses random.choice, which is fine for general purposes. However, for cryptographic-level security, consider using secrets.choice instead of random.choice.

Summary

This Python program is a GUI-based password generator using tkinter.

It allows the user to specify password length and select character types, including letters, numbers, and special characters.

The program then generates a random password based on the selected criteria and displays it in the GUI.

This is a simple yet useful tool to practice using checkboxes, entry fields, and conditional logic in Python.

You may also like