How to Build a Password Manager in Python
Last Updated :
18 Mar, 2024
We have a task to create a Password Manager in Python. In this article, we will see how to create a Password Manager in Python.
What is a Password Manager?
A Password Manager in Python is a tool in which we can add the username and password. Additionally, it allows us to retrieve the username and password. We also have the option to view all added usernames and passwords with just one click. Furthermore, if we want to delete a username and password, we can do so with a single click.
Password Manager in Python
Below is the step-by-step guide for creating a Password Manager in Python:
Create a Virtual Environment
Now, create the virtual environment using the below commands
python -m venv env
.\env\Scripts\activate.ps1
Installation
Here, we will install the following libraries and modules:
- Install Python
- Install Tkinter
Writing the Tkinter Code (app.py)
Below are the step-by-step explanation of the app.py code:
Step 1: User Input and Password Addition
In below code add()
function captures the username and password entered by the user in the Tkinter GUI. It checks if both fields are non-empty. If so, it appends the username and password to a file named "passwords.txt" and displays a success message using a Tkinter messagebox.
Python3
import tkinter as tk
from tkinter import messagebox
def add():
# accepting input from the user
username = entryName.get()
# accepting password input from the user
password = entryPassword.get()
if username and password:
with open("passwords.txt", 'a') as f:
f.write(f"{username} {password}\n")
messagebox.showinfo("Success", "Password added !!")
else:
messagebox.showerror("Error", "Please enter both the fields")
Step 2: Retrieve and Display Password
In below code get()
function retrieves a username entered by the user and reads a file named "passwords.txt" to create a dictionary of username-password pairs. If the entered username exists, it displays the corresponding password; otherwise, it indicates that the username doesn't exist.
Python3
def get():
# accepting input from the user
username = entryName.get()
# creating a dictionary to store the data in the form of key-value pairs
passwords = {}
try:
# opening the text file
with open("passwords.txt", 'r') as f:
for k in f:
i = k.split(' ')
# creating the key-value pair of username and password.
passwords[i[0]] = i[1]
except:
# displaying the error message
print("ERROR !!")
if passwords:
mess = "Your passwords:\n"
for i in passwords:
if i == username:
mess += f"Password for {username} is {passwords[i]}\n"
break
else:
mess += "No Such Username Exists !!"
messagebox.showinfo("Passwords", mess)
else:
messagebox.showinfo("Passwords", "EMPTY LIST!!")
Step 3: Retrieve and Display All Passwords
In below code the getlist()
function reads the "passwords.txt" file, creates a dictionary of all username-password pairs, and displays a messagebox containing the entire list of passwords. If the file is empty, it notifies the user that the list is empty.
Python3
def getlist():
# creating a dictionary
passwords = {}
# adding a try block, this will catch errors such as an empty file or others
try:
with open("passwords.txt", 'r') as f:
for k in f:
i = k.split(' ')
passwords[i[0]] = i[1]
except:
print("No passwords found!!")
if passwords:
mess = "List of passwords:\n"
for name, password in passwords.items():
# generating a proper message
mess += f"Password for {name} is {password}\n"
# Showing the message
messagebox.showinfo("Passwords", mess)
else:
messagebox.showinfo("Passwords", "Empty List !!")
Step 4: Delete User and Update File
In below code the delete()
function takes a username input from the user, reads the "passwords.txt" file, excludes the specified username, and writes the modified data back to the file. If the deletion is successful, it displays a success message; otherwise, it shows an error message.
Python3
def delete():
# accepting input from the user
username = entryName.get()
# creating a temporary list to store the data
temp_passwords = []
# reading data from the file and excluding the specified username
try:
with open("passwords.txt", 'r') as f:
for k in f:
i = k.split(' ')
if i[0] != username:
temp_passwords.append(f"{i[0]} {i[1]}")
# writing the modified data back to the file
with open("passwords.txt", 'w') as f:
for line in temp_passwords:
f.write(line)
messagebox.showinfo(
"Success", f"User {username} deleted successfully!")
except Exception as e:
messagebox.showerror("Error", f"Error deleting user {username}: {e}")
Step 5: Tkinter GUI Setup
below code has main part of the code initializes a Tkinter GUI window, sets its dimensions and title, and creates input fields for username and password. Four buttons are provided for adding passwords (Add
), retrieving a password (Get
), listing all passwords (List
), and deleting a user (Delete
).
Python3
if __name__ == "__main__":
app = tk.Tk()
app.geometry("560x270")
app.title("GeeksForGeeks Password Manager")
# Username block
labelName = tk.Label(app, text="USERNAME:")
labelName.grid(row=0, column=0, padx=15, pady=15)
entryName = tk.Entry(app)
entryName.grid(row=0, column=1, padx=15, pady=15)
# Password block
labelPassword = tk.Label(app, text="PASSWORD:")
labelPassword.grid(row=1, column=0, padx=10, pady=5)
entryPassword = tk.Entry(app)
entryPassword.grid(row=1, column=1, padx=10, pady=5)
# Add button
buttonAdd = tk.Button(app, text="Add", command=add)
buttonAdd.grid(row=2, column=0, padx=15, pady=8, sticky="we")
# Get button
buttonGet = tk.Button(app, text="Get", command=get)
buttonGet.grid(row=2, column=1, padx=15, pady=8, sticky="we")
# List Button
buttonList = tk.Button(app, text="List", command=getlist)
buttonList.grid(row=3, column=0, padx=15, pady=8, sticky="we")
# Delete button
buttonDelete = tk.Button(app, text="Delete", command=delete)
buttonDelete.grid(row=3, column=1, padx=15, pady=8, sticky="we")
app.mainloop()
Complete Code
Below is the complete code for main.py file that we have used in our project.
main.py
Python3
import tkinter as tk
from tkinter import messagebox
def add():
# accepting input from the user
username = entryName.get()
# accepting password input from the user
password = entryPassword.get()
if username and password:
with open("passwords.txt", 'a') as f:
f.write(f"{username} {password}\n")
messagebox.showinfo("Success", "Password added !!")
else:
messagebox.showerror("Error", "Please enter both the fields")
def get():
# accepting input from the user
username = entryName.get()
# creating a dictionary to store the data in the form of key-value pairs
passwords = {}
try:
# opening the text file
with open("passwords.txt", 'r') as f:
for k in f:
i = k.split(' ')
# creating the key-value pair of username and password.
passwords[i[0]] = i[1]
except:
# displaying the error message
print("ERROR !!")
if passwords:
mess = "Your passwords:\n"
for i in passwords:
if i == username:
mess += f"Password for {username} is {passwords[i]}\n"
break
else:
mess += "No Such Username Exists !!"
messagebox.showinfo("Passwords", mess)
else:
messagebox.showinfo("Passwords", "EMPTY LIST!!")
def getlist():
# creating a dictionary
passwords = {}
# adding a try block, this will catch errors such as an empty file or others
try:
with open("passwords.txt", 'r') as f:
for k in f:
i = k.split(' ')
passwords[i[0]] = i[1]
except:
print("No passwords found!!")
if passwords:
mess = "List of passwords:\n"
for name, password in passwords.items():
# generating a proper message
mess += f"Password for {name} is {password}\n"
# Showing the message
messagebox.showinfo("Passwords", mess)
else:
messagebox.showinfo("Passwords", "Empty List !!")
def delete():
# accepting input from the user
username = entryName.get()
# creating a temporary list to store the data
temp_passwords = []
# reading data from the file and excluding the specified username
try:
with open("passwords.txt", 'r') as f:
for k in f:
i = k.split(' ')
if i[0] != username:
temp_passwords.append(f"{i[0]} {i[1]}")
# writing the modified data back to the file
with open("passwords.txt", 'w') as f:
for line in temp_passwords:
f.write(line)
messagebox.showinfo(
"Success", f"User {username} deleted successfully!")
except Exception as e:
messagebox.showerror("Error", f"Error deleting user {username}: {e}")
if __name__ == "__main__":
app = tk.Tk()
app.geometry("560x270")
app.title("GeeksForGeeks Password Manager")
# Username block
labelName = tk.Label(app, text="USERNAME:")
labelName.grid(row=0, column=0, padx=15, pady=15)
entryName = tk.Entry(app)
entryName.grid(row=0, column=1, padx=15, pady=15)
# Password block
labelPassword = tk.Label(app, text="PASSWORD:")
labelPassword.grid(row=1, column=0, padx=10, pady=5)
entryPassword = tk.Entry(app)
entryPassword.grid(row=1, column=1, padx=10, pady=5)
# Add button
buttonAdd = tk.Button(app, text="Add", command=add)
buttonAdd.grid(row=2, column=0, padx=15, pady=8, sticky="we")
# Get button
buttonGet = tk.Button(app, text="Get", command=get)
buttonGet.grid(row=2, column=1, padx=15, pady=8, sticky="we")
# List Button
buttonList = tk.Button(app, text="List", command=getlist)
buttonList.grid(row=3, column=0, padx=15, pady=8, sticky="we")
# Delete button
buttonDelete = tk.Button(app, text="Delete", command=delete)
buttonDelete.grid(row=3, column=1, padx=15, pady=8, sticky="we")
app.mainloop()
Output
Password Manager In Python
Similar Reads
Build a Debian package(.deb) from your Python Program
Creating a Debian package (.deb file) for the Python program allows for easier distribution and installation on the Debian-based systems. Here's a step-by-step guide on how to create a .deb file for the Python program: Build a Debian package(.deb) from your Python ProgramCreating a Debian package fo
2 min read
Personalized Task Manager in Python
In this article, we are going to create a task management software in Python. This software is going to be very useful for those who don't want to burden themselves with which task they have done and which they are left with. Being a coder we have to keep in mind which competition is going on, which
10 min read
How to Import Other Python Files?
We have a task of how to import other Python Files. In this article, we will see how to import other Python Files. Python's modular and reusable nature is one of its strengths, allowing developers to organize their code into separate files and modules. Importing files in Python enables you to reuse
3 min read
Password validation in Python
Let's take a password as a combination of alphanumeric characters along with special characters, and check whether the password is valid or not with the help of few conditions. Conditions for a valid password are: Should have at least one number.Should have at least one uppercase and one lowercase c
4 min read
Remember and copy passwords to clipboard using Pyperclip module in Python
It is always a difficult job to remember all our passwords for different accounts. So this is a really simple Python program which uses sys module to obtain account name as argument from the command terminal and pyperclip module to paste the respective account's password to the clipboard. Pyperclip
2 min read
Python Program to generate one-time password (OTP)
One-time Passwords (OTP) is a password that is valid for only one login session or transaction in a computer or a digital device. Now a days OTPâs are used in almost every service like Internet Banking, online transactions, etc. They are generally combination of 4 or 6 numeric digits or a 6-digit al
2 min read
Generate Random Strings for Passwords in Python
A strong password should have a mix of uppercase letters, lowercase letters, numbers, and special characters. The efficient way to generate a random password is by using the random.choices() method. This method allows us to pick random characters from a list of choices, and it can repeat characters
2 min read
How to Write a Configuration File in Python?
Configuring your Python applications using configuration files is a common practice that allows you to separate configuration details from your code, making it more modular and easier to manage. In this article, we'll explore how to create a configuration file in Python, focusing on a simple and wid
3 min read
Python program to check the validity of a Password
In this program, we will be taking a password as a combination of alphanumeric characters along with special characters, and checking whether the password is valid or not with the help of a few conditions. Primary conditions for password validation: Minimum 8 characters.The alphabet must be between
3 min read
How To Create And Use .env Files In Python
In Python, a .env file is commonly used to store configuration settings, API keys, and other sensitive information. It is a plain text file with key-value pairs, and the python-dotenv library is often used to load these variables into the environment. In this article, we will explore the detailed pr
3 min read