Skip to content
Related Articles

Related Articles

GUI to generate and store passwords in SQLite using Python

Improve Article
Save Article
  • Last Updated : 06 Sep, 2021
Improve Article
Save Article

In this century there are many social media accounts, websites, or any online account that needs a secure password.  Often we use the same password for multiple accounts and the basic drawback to that is if somebody gets to know about your password then he/she has the access to all your accounts. It is hard to remember all the distinct passwords. We can achieve that by creating a simple GUI program using python, Tkinter, and SQLite

This application will generate a password based on the desired length given as input by the user. It will also save the password along with account user_id and the name of the site to a database. You can even update your old password or username. 

Getting Started

The user will specify the length of the password they want to generate.  The program will generate a random string of the specified length using the random function. The user will provide the details of the user ID and the site name associated with the account, and hit the save to database button, which will trigger the insert() function of the file given in the latter part of this article. Hence, saving the data into the database without writing any SQL command. 

Modules used:

  • webbrowser: This module is used to display the help.txt file in notepad.
  • Tkinter: Tkinter is GUI or graphical user interface package in python. It is used for creating GUI applications in python.
  • SQLite3: Sqlite is a lightweight and easy-to-use database engine, which follows similar syntax to that of Postgres SQL. SQLite3 module in python helps us to execute SQL commands using python codes.
  • ttkbootsrtap:  This module changes the appearance of the GUI application. It’s similar to bootstrap in web development, which is used to give a promising look to web pages. This module can be installed in the following ways:


pip install ttkbootstrap

  • csv: This module will help to save the data of the database in a .csv format, which later on be viewed in excel.


pip install python-csv

First, all the required modules are imported. Then 4 lists to represent lowercase, uppercase alphabets, and symbols is initialized, inside the class window as class variables. Then, the whole layout of the application is created under the __init__ function so that all these Tkinter objects are created at the time of declaring an object of the class window. 

Ttkbootstrap package allows you to change the style of the Tkinter objects this includes everything Tkinter has to offer. This will basically change the theme of the application. It comes with many inbuilt themes ex. cyborg, darkly etc.  

Syntax with ttkbootstrap: 


Earlier syntax without ttkbootstrap:

win =Tk()

Password generator Function- generator() runs a loop for chosen password length /4. The length given by the user will always be multiple of 4 since those are the only options given in the dropdown menu. With each iteration choose a random character from the class variable created, using a random function. ex. a0=random.choice(list_name). After choosing and storing the characters from 4 different lists(class variables) into 4 variables of suitable data type, concatenate the 4 variables and store the sum in another variable.

Below is the implementation:

Program: Window to generate passwords


import random
import webbrowser
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import back
import csv
from ttkbootstrap import *
class window:
    # these are lists of initialized characters
    digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    lc = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
          'm', 'n', 'o', 'p', 'q',
          'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    uc = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
          'I', 'J', 'K', 'M', 'N', 'O', 'p', 'Q',
          'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    sym = ['@', '#', '$', '%', '=', ':', '?', '.', '/', '|',
           '~', '>', '*', '<']
    def __init__(self, root, geo, title) -> None:
        self.root = root
        self.root.resizable(width=False, height=False)
        Label(self.root, text='Your Password').grid(
            row=0, column=0, padx=10, pady=10)
        Label(self.root, text='Corresponding User_id').grid(
            row=1, column=0, padx=10, pady=10)
        Label(self.root, text='Of').grid(row=2, column=0, padx=10, pady=10) = StringVar()
        self.user_id = StringVar() = StringVar()
        ttk.Entry(self.root, width=30,
                 ).grid(row=0, column=1, padx=10, pady=10)
        ttk.Entry(self.root, width=30, textvariable=self.user_id
                 ).grid(row=1, column=1, padx=10, pady=10)
        ttk.Entry(self.root, width=30,
                 ).grid(row=2, column=1, padx=10, pady=10)
        self.length = StringVar()
        e = ttk.Combobox(self.root, values=['4', '8', '12', '16', '20', '24'],
        e.grid(row=0, column=2)
        e['state'] = 'readonly'
        self.length.set('Set password length')
        ttk.Button(self.root, text='Generate', padding=5,
                   style='success.Outline.TButton', width=20,
                   command=self.generate).grid(row=1, column=2)
        ttk.Button(self.root, text='Save to Database', style='success.TButton',
                   width=20, padding=5,, column=2)
        ttk.Button(self.root, text='Delete', width=20, style='danger.TButton',
                   padding=5, command=self.erase).grid(row=2, column=2)
        ttk.Button(self.root, text='Show All', width=20, padding=5,
                   command=self.view).grid(row=3, column=0)
        ttk.Button(self.root, text='Update', width=20, padding=5,
                   command=self.update).grid(row=3, column=1)
        # ========self.tree view=============
        self.tree = ttk.Treeview(self.root, height=5)
        self.tree['columns'] = ('site', 'user', 'pas')
        self.tree.column('#0', width=0, stretch=NO)
        self.tree.column('site', width=160, anchor=W)
        self.tree.column('user', width=140, anchor=W)
        self.tree.column('pas', width=180, anchor=W)
        self.tree.heading('#0', text='')
        self.tree.heading('site', text='Site name')
        self.tree.heading('user', text='User Id')
        self.tree.heading('pas', text='Password')
        self.tree.grid(row=4, column=0, columnspan=3, pady=10)
        self.tree.bind("<ButtonRelease-1>", self.catch)
        # this command will call the catch function
        # this is right click pop-up menu = Menu(self.root, tearoff=False)'Refresh', command=self.refresh)'Insert','Update', command=self.update)'Show All', command=self.view)'Clear Fields', command=self.clear)'Clear Table', command=self.table)'Export', command=self.export)'Delete', command=self.erase)'Help','Exit', command=self.root.quit)
        # this binds the button 3 of the mouse with
        self.root.bind("<Button-3>", self.poppin)
        # poppin function
    def help(self):
        # this function will open the help.txt in
        # notepad when called'help.txt')
    def refresh(self):
        # this function basically refreshes the table
        # or tree view
    def table(self):
        # this function will clear all the values
        # displayed in the table
        for r in self.tree.get_children():
    def clear(self):
        # this function will clear all the entry
        # fields'')
    def poppin(self, e):
        # it triggers the right click pop-up menu, e.y_root)
    def catch(self, event):
        # this function will take all the selected data
        # from the table/ tree view and will fill up the
        # respective entry fields'')
        selected = self.tree.focus()
        value = self.tree.item(selected, 'value')[0])
    def update(self):
        # this function will update database with new
        # values given by the user
        selected = self.tree.focus()
        value = self.tree.item(selected, 'value')
        back.edit(, self.user_id.get(),
    def view(self):
        # this will show all the data from the database
        # this is similar to "SELECT * FROM TABLE" sql
        # command
        if back.check() is False:
            messagebox.showerror('Attention Amigo!', 'Database is EMPTY!')
            for row in
                self.tree.insert(parent='', text='', index='end',
                                 values=(row[0], row[1], row[2]))
    def erase(self):
        # this will delete or remove the selected tuple or
        # row from the database
        selected = self.tree.focus()
        value = self.tree.item(selected, 'value')
    def save(self):
        # this function will insert all the data into the
        # database
        back.enter(, self.user_id.get(),
        self.tree.insert(parent='', index='end', text='',
                         values=(, self.user_id.get(),
    def generate(self):
        # this function will produce a random string which
        # will be used as password
        if self.length.get() == 'Set password length':
            messagebox.showerror('Attention!', "You forgot to SELECT")
            a = ''
            for x in range(int(int(self.length.get())/4)):
                a0 = random.choice(self.uc)
                a1 = random.choice(
                a2 = random.choice(self.sym)
                a3 = random.choice(self.digits)
                a = a0+a1+a2+a3+a
    def export(self):
        # this function will save all the data from the
        # database in a csv format which can be opened
        # in excel
        pop = Toplevel(self.root)
        self.v = StringVar()
        Label(pop, text='Save File Name as').pack()
        ttk.Entry(pop, textvariable=self.v).pack()
        ttk.Button(pop, text='Save', width=18,
                   command=lambda: exp(self.v.get())).pack(pady=5)
        def exp(x):
            with open(x + '.csv', 'w', newline='') as f:
                chompa = csv.writer(f, dialect='excel')
                for r in
            messagebox.showinfo("File Saved", "Saved as " + x + ".csv")
if __name__ == '__main__':
    win = Style(theme='darkly').master
    name = 'Password Generator'
    dimension = '565x320'
    app = window(win, dimension, name)

Backend program using SQLite: Sqlite3 module of python allows us to execute sol commands using Python. Following is the syntax

  • It will make a connection to the SQLite database file


  • Cursor for dataset traversal


  • To execute the SQL commands

c.execute(“SQL code”) 

  • Commit or save the changes made


  • This for closing the connection created with SQLite database file


Note: Here the password is been taken as a primary key. So to change the password you need to insert the new one and delete the old one from the database.

Program: Backend program using SQLite:


import sqlite3 as sq
db = 'secure.db'
def connect():
    # used to connect to the secure.db database
    conn = sq.connect(db)
    # defined a cursor to retrieve one data/tuple at
    # a time
    c = conn.cursor()
    # execute will execute the entire sql command as
    # it is
                 CREATE TABLE IF NOT EXISTS data (
                     site text,
                     user text,
                     password text primary key
    # to commit the sql command, it will commit the
    # current transaction or
def enter(site, user, pas):
    conn = sq.connect(db)
    c = conn.cursor()
    c.execute("INSERT INTO data VALUES(?,?,?)", (site, user, pas))
def show():
    conn = sq.connect(db)
    c = conn.cursor()
    c.execute("SELECT * FROM data")
    # this will store all the data from the table to
    # the variable i in the form of 2d list
    i = c.fetchall()
    return i
def Del(password):
    conn = sq.connect(db)
    c = conn.cursor()
    c.execute("DELETE FROM data WHERE password=(?)", (password,))
def edit(site, user, password):
    conn = sq.connect(db)
    c = conn.cursor()
    c.execute("UPDATE data SET site=?, user=(?) WHERE password=(?) ",
              (site, user, password))
def check():
    # this function will check whether the database
    # is empty or not
    if len(show()) == 0:
        return False
        return True
# calling the connect function to create a table and
# database if it doesn't exists





My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!