【python小工具2】随机密码生成器

简介

随机密码生成器是一款简单易用的工具,可以帮助用户快速生成随机密码。该工具使用Python编写,支持多种密码策略,如字母、数字、特殊字符等,并且可以根据用户需求生成不同长度的密码。此外,该工具还提供了一些额外的功能,如对生成的密码根据时间进行缓存、保存生成密码等,

主界面如下:

使用方法

使用方法非常简单,只需要在文本框中输入所需长度和策略,点击生成按钮即可得到一个随机的密码。同时,用户还可以通过该工具对密码进行管理,如保存密码和复制到剪切板等。

使用库

import tkinter as tk # 界面包
from tkinter import messagebox as mb, simpledialog as sp  # 提示弹窗和输入弹窗
import random  # 随机模块
import string  # 字符串
from datetime import datetime  # 生成时间
import pyperclip  # 复制到剪切板

 

生成密码(核心功能)

根据设置的策略生成密码

密码长度

在输入框输入密码的长度,这里加了验证,只能输入数字类型

密码类型

根据选项 可以选择字母(大写、小写、大小写混合)、特俗字符、数字

示例:12位包含大小写字母、不包含特殊字符,包含数字

生成密码代码

def generate_password():
    # 获取设置项的值
    try:
        password_length = int(entry_length.get())
    except ValueError:
        mb.showerror('', '请输入密码位数!')
        return
    include_letters = var_letters.get()
    letter_case = var_case.get()
    include_symbols = var_symbols.get()
    include_numbers = var_numbers.get()
    if not any([include_letters, include_numbers, include_symbols]):
        mb.showerror('', '请选择生成密码的样式')
        return

    # 密码字符集合
    characters = ""

    if include_letters:
        if letter_case == 1:
            characters += string.ascii_lowercase
        elif letter_case == 2:
            characters += string.ascii_uppercase
        else:
            characters += string.ascii_letters

    if include_symbols:
        characters += string.punctuation

    if include_numbers:
        characters += string.digits

    # 生成随机密码
    password = ''.join(random.choice(characters) for _ in range(password_length))

    label_password.delete(1.0, 'end')
    # 显示密码
    label_password.insert(tk.END, chars=password)

 

 

缓存密码

对每次生成的密码进行即时缓存,留下每次生成的痕迹,方便回忆

 

缓存密码区代码

    with open('cache_password.txt', 'a', encoding='utf-8') as file:
        file.write("密码: {}\t生成时间: {}\n".format(password, datetime.now().strftime("%Y-%m-%d %H:%M:%S")))

 

保存密码

将生成的密码保存到密码文件里面,并且添加自定义的备注,防止遗忘

 

保存密码区代码

def save_password():
    password = label_password.get(1.0, tk.END).strip()
    if password:
        remarks = sp.askstring(title='保存密码', prompt='为防止遗忘,请输入保存密码的备注:')
        remarks = remarks.strip()
        if not remarks:
            mb.showinfo('', '未输入备注,保存失败')
            return
        with open('save_password.txt', 'a+', encoding='utf-8') as file:
            file.write(f'备注:{remarks}\n')
            file.write(f'密码:{password}\n')
            file.write(f'时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}\n')
            file.write('-'*30)
            file.write('\n')
        mb.showinfo('', '保存成功')
    else:
        mb.showinfo('', '当前无密码')

 

 

复制密码到剪切板

使用 pyperclip 模块,可以进通过执行 pip install pyperclip 进行安装

复制到剪切板区代码

def copy_password():
    """
    复制密码到剪切板
    :return:
    """
    password = label_password.get(1.0, 'end')
    if password:
        pyperclip.copy(password)
        mb.showinfo('', '复制成功')
    else:
        mb.showinfo('', '当前无密码')

完整代码

import tkinter as tk # 界面包
from tkinter import messagebox as mb, simpledialog as sp  # 提示弹窗和输入弹窗
import random  # 随机模块
import string  # 字符串
from datetime import datetime  # 生成时间
import pyperclip  # 复制到剪切板


BACKGROUND = 'white'


def copy_password():
    """
    复制密码到剪切板
    :return:
    """
    password = label_password.get(1.0, 'end')
    if password:
        pyperclip.copy(password)
        mb.showinfo('', '复制成功')
    else:
        mb.showinfo('', '当前无密码')

def generate_password():
    # 获取设置项的值
    try:
        password_length = int(entry_length.get())
    except ValueError:
        mb.showerror('', '请输入密码位数!')
        return
    include_letters = var_letters.get()
    letter_case = var_case.get()
    include_symbols = var_symbols.get()
    include_numbers = var_numbers.get()
    if not any([include_letters, include_numbers, include_symbols]):
        mb.showerror('', '请选择生成密码的样式')
        return

    # 密码字符集合
    characters = ""

    if include_letters:
        if letter_case == 1:
            characters += string.ascii_lowercase
        elif letter_case == 2:
            characters += string.ascii_uppercase
        else:
            characters += string.ascii_letters

    if include_symbols:
        characters += string.punctuation

    if include_numbers:
        characters += string.digits

    # 生成随机密码
    password = ''.join(random.choice(characters) for _ in range(password_length))

    label_password.delete(1.0, 'end')
    # 显示密码
    label_password.insert(tk.END, chars=password)

    # 保存密码到文件
    with open('cache_password.txt', 'a', encoding='utf-8') as file:
        file.write("密码: {}\t生成时间: {}\n".format(password, datetime.now().strftime("%Y-%m-%d %H:%M:%S")))

    button_copy.config(state=tk.NORMAL)


def save_password():
    password = label_password.get(1.0, tk.END).strip()
    if password:
        remarks = sp.askstring(title='保存密码', prompt='为防止遗忘,请输入保存密码的备注:')
        remarks = remarks.strip()
        if not remarks:
            mb.showinfo('', '未输入备注,保存失败')
            return
        with open('save_password.txt', 'a+', encoding='utf-8') as file:
            file.write(f'备注:{remarks}\n')
            file.write(f'密码:{password}\n')
            file.write(f'时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}\n')
            file.write('-'*30)
            file.write('\n')
        mb.showinfo('', '保存成功')
    else:
        mb.showinfo('', '当前无密码')


def center_window(windows):
    window.update_idletasks()
    screen_width = window.winfo_screenwidth()
    screen_height = window.winfo_screenheight()
    window_width = window.winfo_width()
    window_height = window.winfo_height()
    x = (screen_width - window_width) // 2
    y = (screen_height - window_height) // 2
    window.geometry('{}x{}+{}+{}'.format(window_width, window_height, x, y))


def letter():
    if var_letters.get():
        radio_case_lower.config(state='normal')
        radio_case_upper.config(state='normal')
        radio_case_mixed.config(state='normal')
    else:
        radio_case_lower.config(state='disabled')
        radio_case_upper.config(state='disabled')
        radio_case_mixed.config(state='disabled')


def validate_command(text):
    if text.isdigit():
        if int(text) >= 0:
            return True
    mb.showerror('', '请输入数字')
    return False


# 创建窗口
window = tk.Tk()
window.title("密码生成器--@程甲第")
window_width = 350
window_height = 260
window.geometry('{}x{}'.format(window_width, window_height))
center_window(window)
window.config(background=BACKGROUND)
frame0 = tk.Frame(window)
frame0.config(background=BACKGROUND)
frame0.pack(expand=True, fill=tk.BOTH)
frame1 = tk.Frame(frame0)
frame1.config(background=BACKGROUND)
frame1.pack(expand=True, fill=tk.BOTH)
frame3 = tk.Frame(frame1)
frame3.config(background=BACKGROUND)
frame3.pack(expand=True, fill=tk.X)
frame4 = tk.Frame(frame1)
frame4.config(background=BACKGROUND)
frame4.pack(expand=True, fill=tk.X)
frame5 = tk.Frame(frame1)
frame5.config(background=BACKGROUND)
frame5.pack(expand=True, fill=tk.X)
frame6 = tk.Frame(frame1)
frame6.config(background=BACKGROUND)
frame6.pack(expand=True, fill=tk.X)
frame7 = tk.Frame(frame1)
frame7.config(background=BACKGROUND)
frame7.pack(expand=True, fill=tk.X)
# 密码位数输入框和标签
label_length = tk.Label(frame3, text="密码长度:")
label_length.config(background=BACKGROUND)
label_length.pack(side=tk.LEFT)
entry_length = tk.Entry(frame3, validate="key", validatecommand=(window.register(validate_command), '%S'))
entry_length.pack(side=tk.LEFT, expand=True, fill=tk.X)

# 字母选择复选框
var_letters = tk.BooleanVar()
var_letters.set(False)
check_letters = tk.Checkbutton(frame4, text="包括字母", variable=var_letters, command=letter)
check_letters.config(background=BACKGROUND)
check_letters.pack(side=tk.LEFT)

# 字母大小写选择单选框
var_case = tk.IntVar()
radio_case_lower = tk.Radiobutton(frame4, text="小写字母", variable=var_case, value=1, state=tk.DISABLED)
radio_case_lower.config(background=BACKGROUND)
radio_case_lower.pack(side=tk.LEFT)
radio_case_upper = tk.Radiobutton(frame4, text="大写字母", variable=var_case, value=2, state=tk.DISABLED)
radio_case_upper.config(background=BACKGROUND)
radio_case_upper.pack(side=tk.LEFT)
radio_case_mixed = tk.Radiobutton(frame4, text="大小写混合", variable=var_case, value=3, state=tk.DISABLED)
radio_case_mixed.config(background=BACKGROUND)
radio_case_mixed.pack(side=tk.LEFT)

# 特殊符号选择复选框
var_symbols = tk.BooleanVar()
check_symbols = tk.Checkbutton(frame5, text="包含特殊符号", variable=var_symbols)
check_symbols.config(background=BACKGROUND)
check_symbols.pack(side=tk.LEFT)

# 数字选择复选框
var_numbers = tk.BooleanVar()
check_numbers = tk.Checkbutton(frame5, text="包含数字", variable=var_numbers)
check_numbers.config(background=BACKGROUND)
check_numbers.pack(side=tk.LEFT)

# 生成密码按钮
button_generate = tk.Button(frame6, text="生成密码", command=generate_password)
button_generate.config(background='#57965c', foreground='white', borderwidth=0)
button_generate.pack(side=tk.LEFT, padx=5, pady=5)
button_copy = tk.Button(frame6, text="保存密码", command=save_password)
button_copy.config(background='#26445e', foreground='white', borderwidth=0)
button_copy.pack(side=tk.LEFT, padx=5, pady=5)
button_copy = tk.Button(frame6, text="复制密码到剪切板", command=copy_password, state=tk.DISABLED)
button_copy.config(background='#399cfd', foreground='white', borderwidth=0)
button_copy.pack(side=tk.LEFT, padx=5, pady=5)
# 生成的密码标签
label_password = tk.Text(frame7, background=BACKGROUND, foreground='red')
label_password.pack(side=tk.LEFT, padx=5, pady=5, expand=True, fill=tk.X)
label_password.see('9.0')
# 运行窗口
window.mainloop()

此外也对代码进行打包,生成了可执行文件exe, 由于使用的python版本为3.12,因此打包的exe 仅支持win10 及以上他可以运行

 

阅读剩余
本文发布于2024-02-20部分内容具有时效性,如有失效,请联系邮箱:heiyingcyh@163.com
THE END