How You Can Create a GUI Password Generator in Python

·

5 min read

Hi readers! Here is another simple tutorial that will teach you how to create another real-life use script!

In this tutorial, we’ll be building a password generator with GUI using python and Tkinter.

This is a great project for beginners because it’s relatively simple and can be completed in a short amount of time.

Plus, it’s a great way to learn how to use python and Tkinter to create a GUI application.

As I said, we will use the Tkinter library to create the Graphic User Interface, it’s an awesome library that provides an easy way to create GUI with python.

The password generator project will consist of:

  • Two options menu for choosing length and chars to use

  • A text box that outputs the result

  • A button to close the Window

  • A button for generating the password

This is how it will appear!

We’ll take a step-by-step look at all the main aspects.

Prerequisites:

The only libraries we will use are the ones we already have. So you won’t need to install anything.

We will use many of the functions we used in these two articles:

This is a list of the libraries mentioned above:

  • strings: library for common string operations, we need it to get the “population” of characters from which we pick random elements.

  • random: is in charge of a lot of functions in this case we will use it to random choose from a list of characters

  • Tkinter we have already seen it, this is the python core library to manage the graphical interface.

I think we are ready to go and create our wonderful application!

Creating the GUI

The approach will be similar to what we did in the previous articles.

We will create a class “Window” that will build the whole interface inside its initUI method!

First of all, let’s define the class and some static variables for the configuration!

import tkinter
import string
import random
class Window():MAX_CHARS = 15
    MIN_CHARS = 3
    CHARS_OPTIONS = ["Alphanumeric", 
                    "Numeric", 
                    "Alpha"]
    GRID_PADY = (18, 18)
    def __init__(self):
        self.initUI()

The code above initializes the Tkinter GUI and:

  • Sets the maximum number of password characters to 15

  • Sets the minimum number of password characters to 3

  • Sets the character options to an array containing alphanumeric, numeric, and alpha values.
    They are the character set for building the random password

  • Sets the vertical padding for the grid to 18 pixels (we’ll use it in our elements).

The next step is to work on initUI method:

def initUI(self):# Construction of the root element
        self.master = tkinter.Tk()
        self.master.title("Password Generator")
        self.master.geometry("580x250")


        self.ptype = tkinter.StringVar(self.master, 
                                    value=Window.CHARS_OPTIONS[0])
        self.n_chars = tkinter.IntVar(self.master, 
                                    value=Window.MIN_CHARS)

The first lines are:

  • Creating the root

  • Setting the title and size of the window

  • Setting the default values in the option menus

Now it's time to choose our layout

According to my tastes, the layout that best suits our needs could be the grid layout.
So first, we create all the elements, and then we will insert them into the grid.

Let’s see the code that creates:

  • An options menu for selecting the characters set to use and its Label

  • An options menu for selecting the password’s length and its Label

  • Text box where to output the password

  • Generate and Close buttons

# Creates a label 
self.label_chars = tkinter.Label(self.master,
                text='Chars that will compose the Password: ')
# The option menu for the character set 
self.option_menu_chars = tkinter.OptionMenu(self.master,
                self.ptype, *Window.CHARS_OPTIONS)

self.frame_n_chars = tkinter.Frame(self.master)
        self.label_num_chars = tkinter.Label(self.master,
                text='Password Length:')

# Option menu for setting the password length, the option are the
# Result of expanding the range function

self.option_menu_n_chars = tkinter.OptionMenu(self.master,
                self.n_chars, *range(Window.MIN_CHARS, 
Window.MAX_CHARS
                + 1))

self.text_password_out = tkinter.Text(self.master, border=2,
                height=2, width=30)

self.frame_buttons = tkinter.Frame()
        self.button_generate = tkinter.Button(self.frame_buttons,
                text='Generate', width=8, command=lambda : \
                self.set_password())
        self.button_close = tkinter.Button(self.frame_buttons,
                text='Close', command=self.master.quit, width=8)

At this point, we created all the widgets and all their parameters, so we need two things again:

  • Place them inside the grid

  • Write the set_command callback method

The grid is very simple to use, we do need just to specify the row and the columns where to place the selected widget.

Let’s see how:

self.label_num_chars.grid(row=1, column=0,
                          pady=Window.GRID_PADY)
self.option_menu_n_chars.grid(row=1, column=1)
self.text_password_out.grid(row=2, column=0,
                          pady=Window.GRID_PADY)
self.button_generate.pack(side=tkinter.LEFT)
self.button_close.pack(side=tkinter.LEFT, pady=Window.GRID_PADY)
self.frame_buttons.grid(row=3, column=1, columnspan=2)
self.master.mainloop()

Now let’s take a look at the set_password() method.

def set_password(self):
        chars = ''
        ptype = self.ptype.get().lower()
        if ptype == 'numeric':
            chars = string.digits
        elif ptype == 'alpha':
            chars = string.ascii_letters
        else:
            chars = string.digits + string.ascii_letters

        password = ''.join(random.choices(chars,  
                          k=self.n_chars.get()))

        self.text_password_out.delete('1.0', tkinter.END)
        self.text_password_out.insert('1.0', password)

The method will generate a random password that is either all letters, all numbers, or a combination of both (depending on what it finds in the ptype variable that is set by the options menu). After that, it set the textbox with the generated value.

Before saying goodbye I would like to show you the complete code.

import tkinter
import string
import random
class Window():

    MAX_CHARS = 15
    MIN_CHARS = 3
    CHARS_OPTIONS = ["Alphanumeric", 
                    "Numeric", 
                    "Alpha"]
    GRID_PADY = (18, 18)
    def __init__(self):
        self.initUI()


    def initUI(self):

        # Construction of the root element
        self.master = tkinter.Tk()
        self.master.title("Password Generator")
        self.master.geometry("580x250")


        self.ptype = tkinter.StringVar(self.master, 
                                    value=Window.CHARS_OPTIONS[0])
        self.n_chars = tkinter.IntVar(self.master, 
                                    value=Window.MIN_CHARS)

        self.label_chars = tkinter.Label(self.master, 
                text="Chars that will compose the Password: ")
        self.option_menu_chars = tkinter.OptionMenu(self.master, self.ptype ,*Window.CHARS_OPTIONS)



        self.frame_n_chars = tkinter.Frame(self.master) 
        self.label_num_chars = tkinter.Label(self.master, text="Password Length:")
        self.option_menu_n_chars = tkinter.OptionMenu(self.master, self.n_chars, *range(Window.MIN_CHARS, Window.MAX_CHARS+1))


        self.text_password_out = tkinter.Text(self.master, border=2, height=2, width=30)

        self.frame_buttons = tkinter.Frame()
        self.button_generate = tkinter.Button(self.frame_buttons, text="Generate", width=8, command=lambda: self.set_password())
        self.button_close = tkinter.Button(self.frame_buttons, text="Close", command=self.master.quit, width=8)

        self.label_chars.grid(row=0, column=0, pady=Window.GRID_PADY)
        self.option_menu_chars.grid(row=0, column=1)


        self.label_num_chars.grid(row=1, column=0, pady=Window.GRID_PADY)
        self.option_menu_n_chars.grid(row=1, column=1)


        self.text_password_out.grid(row=2, column=0, pady=Window.GRID_PADY)

        self.button_generate.pack(side=tkinter.LEFT)
        self.button_close.pack(side=tkinter.LEFT, pady=Window.GRID_PADY)
        self.frame_buttons.grid(row=3, column=1, columnspan=2)



        self.master.mainloop()

    def set_password(self):
        chars = ""
        ptype = self.ptype.get().lower()
        if ptype == "numeric":
            chars = string.digits

        elif ptype == "alpha":
            chars = string.ascii_letters
        else:
            chars = string.digits + string.ascii_letters   

        password = "".join(random.choices(chars, k=self.n_chars.get()))

        self.text_password_out.delete("1.0", tkinter.END)
        self.text_password_out.insert("1.0", password)





if __name__=="__main__":
    Window()

Conclusion

Thanks for reading! I hope this article has helped you understand how to code a GUI password generator in python. If you have either any questions or suggestions, please feel free to leave a comment below and I will get back to you as soon as possible.

Thank you again for your time, and if you like my articles please follow me or take a look at my blog StackZero.