Random password generator with a graphical user interface

Random password generator with a graphical user interface

Creating a Random Password Generator with a Graphical User Interface (GUI)

In this article, we will explore how to create a random password generator with a graphical user interface (GUI). We will use the Python programming language and the tkinter library. This project is ideal for beginner programmers who want to learn the basics of creating GUI applications.

Requirements and Necessary Libraries

To create this application, we will need the following libraries:

  • tkinter to create the graphical user interface.
  • random for generating random characters.
  • string for accessing character sets such as letters, digits, and punctuation.

Setting Up the GUI

The first step is to set up the graphical user interface. We use the tkinter library to create a window with labels, entry fields, and buttons.

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

 

We start by importing the necessary libraries. tkinter is used for the GUI, while random and string help us generate the passwords.

class PasswordGeneratorGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("Password Generator")
        self.root.geometry("400x300")
        self.root.config(bg="#1e1e1e")

 

In the PasswordGeneratorGUI class, we define the main structure of our application. The __init__ method initializes the main window with a title, size, and background color.

Adding Labels and Entry Fields

Next, we add labels and entry fields to guide the user.

self.title_label = tk.Label(self.root, text="Password Generator", font=("Helvetica", 18, "bold"), bg="#1e1e1e", fg="#00FF00")
self.title_label.pack(pady=10)
self.length_label = tk.Label(self.root, text="Password Length:", font=("Helvetica", 12), bg="#1e1e1e", fg="#FFFFFF")
self.length_label.pack(pady=5)
self.length_entry = tk.Entry(self.root, font=("Helvetica", 12))
self.length_entry.pack(pady=5)

 

We create a title label and a label for the password length. The entry field allows the user to input the desired length of the password.

Creating the Generate Button

We add a button to trigger the password generation.

self.generate_button = tk.Button(self.root, text="Generate Password", font=("Helvetica", 12, "bold"), bg="#00FF00", fg="#1e1e1e", command=self.generate_password)
self.generate_button.pack(pady=10)

 

The generate_button triggers the generate_password method, which handles the logic for generating a password.

Displaying the Generated Password

We also need to display the generated password to the user.

self.password_label = tk.Label(self.root, text="", font=("Helvetica", 14), bg="#1e1e1e", fg="#FFFFFF")
self.password_label.pack(pady=10)

 

This label will be updated with the generated password once the user clicks the “Generate Password” button.

Copying the Password to Clipboard

To enhance usability, we add a button that allows the user to copy the generated password to the clipboard.

self.copy_button = tk.Button(self.root, text="Copy to Clipboard", font=("Helvetica", 12, "bold"), bg="#00FF00", fg="#1e1e1e", command=self.copy_to_clipboard)
self.copy_button.pack(pady=5)

 

Generating the Password

The main functionality of our application is handled by the generate_password method.

def generate_password(self):
    length = self.length_entry.get()
    if not length.isdigit():
        messagebox.showerror("Invalid Input", "Please enter a valid number for the length.")
        return
    length = int(length)
    if length < 4:
        messagebox.showerror("Invalid Input", "Password length should be at least 4 characters.")
        return
    characters = string.ascii_letters + string.digits + string.punctuation
    password = ''.join(random.choice(characters) for _ in range(length))
    self.password_label.config(text=password)

 

This method checks if the input is a valid number and generates a password of the specified length. The password is composed of letters, digits, and punctuation characters.

Copying the Password to Clipboard

The copy_to_clipboard method allows the user to copy the generated password.

def copy_to_clipboard(self):
    password = self.password_label.cget("text")
    if password:
        self.root.clipboard_clear()
        self.root.clipboard_append(password)
        messagebox.showinfo("Success", "Password copied to clipboard!")
    else:
        messagebox.showwarning("No Password", "Please generate a password first.")

 

This method copies the password to the clipboard and displays a confirmation message.

Running the Application

Finally, we create an instance of our application and start the main loop.

if __name__ == "__main__":
    root = tk.Tk()
    app = PasswordGeneratorGUI(root)
    root.mainloop()

 

This block initializes the GUI application and keeps it running until the user closes it.

import tkinter as tk
from tkinter import messagebox
import random
import string
class PasswordGeneratorGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("Password Generator")
        self.root.geometry("400x300")
        self.root.config(bg="#1e1e1e")
        self.title_label = tk.Label(self.root, text="Password Generator", font=("Helvetica", 18, "bold"), bg="#1e1e1e", fg="#00FF00")
        self.title_label.pack(pady=10)
        self.length_label = tk.Label(self.root, text="Password Length:", font=("Helvetica", 12), bg="#1e1e1e", fg="#FFFFFF")
        self.length_label.pack(pady=5)
        self.length_entry = tk.Entry(self.root, font=("Helvetica", 12))
        self.length_entry.pack(pady=5)
        self.generate_button = tk.Button(self.root, text="Generate Password", font=("Helvetica", 12, "bold"), bg="#00FF00", fg="#1e1e1e", command=self.generate_password)
        self.generate_button.pack(pady=10)
        self.password_label = tk.Label(self.root, text="", font=("Helvetica", 14), bg="#1e1e1e", fg="#FFFFFF")
        self.password_label.pack(pady=10)
        self.copy_button = tk.Button(self.root, text="Copy to Clipboard", font=("Helvetica", 12, "bold"), bg="#00FF00", fg="#1e1e1e", command=self.copy_to_clipboard)
        self.copy_button.pack(pady=5)
    def generate_password(self):
        length = self.length_entry.get()
        if not length.isdigit():
            messagebox.showerror("Invalid Input", "Please enter a valid number for the length.")
            return
        length = int(length)
        if length < 4:
            messagebox.showerror("Invalid Input", "Password length should be at least 4 characters.")
            return
        characters = string.ascii_letters + string.digits + string.punctuation
        password = ''.join(random.choice(characters) for _ in range(length))
        self.password_label.config(text=password)
    def copy_to_clipboard(self):
        password = self.password_label.cget("text")
        if password:
            self.root.clipboard_clear()
            self.root.clipboard_append(password)
            messagebox.showinfo("Success", "Password copied to clipboard!")
        else:
            messagebox.showwarning("No Password", "Please generate a password first.")
if __name__ == "__main__":
    root = tk.Tk()
    app = PasswordGeneratorGUI(root)
    root.mainloop()

Conclusion

This article walked through the steps to create a random password generator with a graphical interface using Python and tkinter. This project is a great way to practice creating simple yet functional GUI applications. The script is easy to modify and expand, allowing you to add more features or customize the appearance to suit your preferences.

Random password generator

Fedya Serafiev

Fedya Serafiev

Fedya Serafiev owns the website linuxcodelab.eu. He finds satisfaction in helping people solve even the most complex technical problems. His current goal is to write easy-to-follow articles so that such problems do not arise at all.

Thank you for reading the article! If you found the information useful, you can donate using the buttons below: