Home » General Python Tutorials » How to Generate Random Passwords in Python

How to Generate Random Passwords in Python

Anyone using the internet knows the importance of a strong password as such in this article we’re going to build a strong password generator interface in which the user can choose the length of the password that is going to be formed by different characters by using a python library named tkinter. So without further ado let us start.

Table of Contents

Necessary Libraries

Make sure to install the tkinter library for the code to function properly:

$ pip install tk

Imports

First of all, we import everything from tkinter allowing us to use everything in it, then we import randint from random to generate random integers, which are whole numbers so that we can use the ASCII table that turns integers into different characters.

from tkinter import *
from random import randint

PasswordGenerator Class and Main Window

class PasswordGenerator:
   def __init__(self, master):
       self.master = master
       self.master.title('Password Generator - The PyCodes')
       self.master.geometry("400x250")
       self.master.configure(bg="black")

Next, we define the class of our program which is basically a blueprint for our password generator, then initialize it and name the main window as well as define its geometry and its background color.

Password Length and Returned Password

Password Length Label Frame

       # Create password length LabelFrame
       length_frame = LabelFrame(self.master, text="How many characters do you want?",bg="black",fg="white")
       length_frame.pack(pady=20)

What we did here is create a label frame that asks how many characters the user wants in his password.

Password Length Entry Box

       # Create password length entry box
       self.password_length = Entry(length_frame, font=("arial", 20),bg="grey",fg="black")
       self.password_length.pack(pady=10)

Then we create an entry box where the user can input the desired length for the password.

Returned Password Entry Box

       # Create returned password entry box
       self.returned_password = Entry(self.master, text='', font=("arial", 20),bg="grey",fg="black")
       self.returned_password.pack(pady=10)

Here, we created an entry box where our generated password appears.

Creating Buttons

       # Create button frame
       button_frame = Frame(self.master)
       button_frame.pack(pady=10)

       # Create generating password button
       pass_button = Button(button_frame, text="Generate Password", command=self.generate_password,bg="green",fg="white")
       pass_button.grid(row=0, column=0)

After that, we create a frame that is going to hold our button, then create the said button “Generate Password” and make it so that once clicked it triggers the generate_password function.

Generate Password Function

   def generate_password(self):
       # Clear returned_password entry box
       self.returned_password.delete(0, END)


       try:
           # Get password length in integer
           pass_number = int(self.password_length.get())
       except ValueError:
           # Handle non-integer input for password length
           self.returned_password.insert(0, "Invalid input. Please enter a valid number.")
           return

       # Create password variable
       password = ''

       # Loop through password length
       for _ in range(pass_number):
           password += chr(randint(33, 126))  # Adjusted the range to include more printable characters

       # Show the password on the returned_password entry box
       self.returned_password.insert(0, password)

Following that, we define a function that is going to generate the password by:

  • First, make sure the password display entry box is empty; if not, it deletes the content in it.
  • Second, it transforms the input into a random integer within the ASCII range of printable characters (33 to 126) after making sure it’s a correct number because if it’s not an error message pops up.
  • Third, it generates a password by making the random integer into the corresponding ASCII character and repeats this process of iterations until it forms a string of ASCII characters that matches the length of the desired password.
  • Lastly, it displays the generated password.

Main Function

def main():
   window = Tk()
   app = PasswordGenerator(window)
   window.mainloop()

What we did here is simply make sure the main window keeps running until the user exits willingly.

Entry Point

if __name__ == "__main__":
   main()

Finally, this part makes sure that the script runs only when the user runs it directly as a script not as a module.

Example

Full Code

from tkinter import *
from random import randint


class PasswordGenerator:
   def __init__(self, master):
       self.master = master
       self.master.title('Password Generator - The PyCodes')
       self.master.geometry("400x250")
       self.master.configure(bg="black")


       # Create password length LabelFrame
       length_frame = LabelFrame(self.master, text="How many characters do you want?",bg="black",fg="white")
       length_frame.pack(pady=20)


       # Create password length entry box
       self.password_length = Entry(length_frame, font=("arial", 20),bg="grey",fg="black")
       self.password_length.pack(pady=10)


       # Create returned password entry box
       self.returned_password = Entry(self.master, text='', font=("arial", 20),bg="grey",fg="black")
       self.returned_password.pack(pady=10)


       # Create button frame
       button_frame = Frame(self.master)
       button_frame.pack(pady=10)


       # Create generating password button
       pass_button = Button(button_frame, text="Generate Password", command=self.generate_password,bg="green",fg="white")
       pass_button.grid(row=0, column=0)


   def generate_password(self):
       # Clear returned_password entry box
       self.returned_password.delete(0, END)


       try:
           # Get password length in integer
           pass_number = int(self.password_length.get())
       except ValueError:
           # Handle non-integer input for password length
           self.returned_password.insert(0, "Invalid input. Please enter a valid number.")
           return


       # Create password variable
       password = ''


       # Loop through password length
       for _ in range(pass_number):
           password += chr(randint(33, 126))  # Adjusted the range to include more printable characters


       # Show the password on the returned_password entry box
       self.returned_password.insert(0, password)




def main():
   window = Tk()
   app = PasswordGenerator(window)
   window.mainloop()


if __name__ == "__main__":
   main()

Happy Coding!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top