T 流年印迹
流年印迹
首页 Python 正文

Python 100 天 · 第 29 天:密码管理器(上):界面与本地存储

这是「Python 100 天」系列第 29 天的学习笔记:密码管理器(上):界面与本地存储。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

一个本地密码本:填网站、账号、密码,点 Add 追加保存到 data.txt;点 Generate Password 自动生成强密码并复制到剪贴板。README 知识点:图片与 Canvas、grid 与 columnspan、保存到文件、弹窗对话框、生成密码与剪贴板。

一、columnspan:跨列

1
website_entry.grid(column=1, row=1, columnspan=2)

columnspan=2 表示这个控件横跨两列,视觉上更宽。rowspan 同理跨行。这是 grid 布局做"输入框占满右侧"的标准手法。

二、输入框操作

1
2
3
4
entry.get()               # 取内容,永远是 str
entry.insert(0, "默认值") # 在位置 0 插入
entry.delete(0, END) # 清空(从 0 删到末尾)
entry.focus() # 启动时聚焦,光标直接在里面

三、弹窗

1
2
3
4
5
6
7
from tkinter import messagebox

messagebox.showinfo(title, message) # 提示
messagebox.showwarning(title, message) # 警告
messagebox.showerror(title, message) # 错误
messagebox.askokcancel(title, message) # 返回 True/False
messagebox.askyesno(title, message) # 返回 True/False

askokcancel 会阻塞直到用户点击,返回值可以直接放在 if 里——这是"保存前二次确认"的标准做法。

四、生成密码与剪贴板

1
2
3
4
from random import choice, randint, shuffle
import pyperclip

pyperclip.copy(password) # 复制到系统剪贴板(需 pip install pyperclip)

密码生成的三步:按类别各取若干字符 → shuffle 打乱 → "".join。分类抽取保证了"一定含数字和符号",打乱保证了"不是字母全在前"。

代码全文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
from tkinter import *
from tkinter import messagebox
from random import choice, randint, shuffle
import pyperclip


def generate_password():
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v',
'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']

password_list = [choice(letters) for _ in range(randint(8, 10))]
password_list += [choice(symbols) for _ in range(randint(2, 4))]
password_list += [choice(numbers) for _ in range(randint(2, 4))]

shuffle(password_list)

password = "".join(password_list)
pyperclip.copy(password)

password_entry.insert(0, password)


def save():
website = website_entry.get()
email = email_username_entry.get()
password = password_entry.get()

if len(password) == 0 or len(website) == 0:
messagebox.showwarning(title="Empty fields", message="Please don't leave any empty fields")
elif messagebox.askokcancel(title=website, message=f"You've entered: nEmail: {email}nPassword: {password}"
f"nIs it OK to save?"):
with open("data.txt", mode="a") as file:
file.write(f"{website} | {email} | {password}n")
website_entry.delete(0, END)
password_entry.delete(0, END)


window = Tk()
window.title("Password Manager")
window.config(padx=25, pady=25)

canvas = Canvas(width=200, height=200)
logo_png = PhotoImage(file="logo.png")
canvas.create_image(100, 100, image=logo_png)
canvas.grid(column=1, row=0)

website_label = Label(text="Website:")
website_label.grid(column=0, row=1)
email_username_label = Label(text="Email/Username:")
email_username_label.grid(column=0, row=2)
password_label = Label(text="Password:", width=21)
password_label.grid(column=0, row=3)

generate_button = Button(text="Generate Password", width=21, command=generate_password)
generate_button.grid(column=2, row=3, columnspan=2)
add_button = Button(text="Add", width=36, command=save)
add_button.grid(column=1, row=4, columnspan=2)

website_entry = Entry(width=35)
website_entry.grid(column=1, row=1, columnspan=2)
website_entry.focus()
email_username_entry = Entry(width=35)
email_username_entry.grid(column=1, row=2, columnspan=2)
email_username_entry.insert(0, "[email protected]")
password_entry = Entry(width=22)
password_entry.grid(column=1, row=3)


window.mainloop()

代码走读

  1. generate_password():三行推导式分别生成 8~10 个字母、2~4 个符号、2~4 个数字,拼成一个列表。
  2. shuffle(password_list):原地打乱,没有返回值。
  3. pyperclip.copy(password) + password_entry.insert(0, password):既进剪贴板又填进输入框,用户可直接粘贴使用。
  4. save():取三个字段 → 校验非空 → askokcancel 二次确认 → 以追加模式写入。
  5. 写入格式:网站 | 账号 | 密码,用 | 分隔,行尾 n。这就是最朴素的数据库,后面换成 JSON、SQLite 都是为了解决"怎么查、怎么改"。
  6. 保存成功后清空网站和密码输入框,账号保留(同一个人常用同一个邮箱)。

这份代码的问题

  • 明文存储:data.txt 里密码是明文,任何能读文件的人都能看到。真实产品必须加密(至少 hashlib 存哈希,或 cryptography 加密)。这是"教学项目"和"能用的产品"的差距,必须心里有数。
  • | 作为分隔符不安全:密码里如果有 |,解析就会错位。CSV 用引号转义,JSON 用结构,正是为了解决这个问题。
  • generate_password 没有清空旧值:连续点两次,输入框里会变成"旧密码新密码"拼在一起。应先 password_entry.delete(0, END)。
  • 网站名大小写不统一:Google 和 google 会存成两条。

运行效果

窗口上方是锁图标,三行输入(Website / Email / Password),右侧 Generate 与 Search,底部 Add。点 Add 弹出确认框,确认后写入 data.txt。

易错点

  1. insert(0, ...) 的 0 是"插入位置",不是"第 0 个字符之后"。
  2. delete(0, END) 的 END 要大写(是 Tkinter 常量)。
  3. 忘了 import pyperclip 或没装包:ModuleNotFoundError。
  4. askokcancel 返回 "ok" 字符串——不,它返回布尔值;但 askquestion 返回 "yes"/"no",容易记混。
  5. 覆盖 vs 追加:这里用 a 是对的,用 w 会把之前所有密码清空。

动手改

  • 生成密码前先清空输入框。
  • 网站名统一 .title() 或 .lower()。
  • 把存储改成 JSON(Day 30 就做这件事)。

源文件逐个讲解

3 个文件 + 1 张图:

文件 规模 职责
main.py75 行密码管理器 1.0:生成随机密码 + 保存到文本
data.txt2 行运行产物:一条记录
logo.png14KB界面 logo
README.md10 行说明页

data.txt(2 行)

1
Amazon | [email protected] | wJ(28#RlN)mLfOz

一行一条记录,用 | 分隔三个字段。这是最原始的「数据库」——没有表头、没有转义。

致命隐患:如果网站名里本身带 | (或者邮箱里带),这条记录就没法正确切分。真实项目会用 CSV(带引号转义)或 JSON。

main.py(75 行)

(1)generate_password():三段生成 + 打乱

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def generate_password():
letters = ['a', ..., 'Z']
numbers = ['0', ..., '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']

password_list = [choice(letters) for _ in range(randint(8, 10))]
password_list += [choice(symbols) for _ in range(randint(2, 4))]
password_list += [choice(numbers) for _ in range(randint(2, 4))]

shuffle(password_list)

password = "".join(password_list)
pyperclip.copy(password)

password_entry.insert(0, password)

和 Day 05 的手写密码生成器对比,进步很明显:

Day 05 Day 29
三个 for 循环三个列表推导
randint(0, 51) 魔法数字choice(letters) 自动适应长度
没有保证字符种类保证至少 2 符号 + 2 数字
''.join(password)一样

pyperclip.copy(password) 把密码直接放进剪贴板——第三方库,需要 pip install pyperclip。这是「提升体验」的一行,省了手动复制。

password_entry.insert(0, password) 是个 bug 温床:insert(0, ...) 是「在下标 0 插入」,不是替换。连点两次「Generate Password」,输入框里就有两个密码拼在一起。

正确写法是先清空:

1
2
password_entry.delete(0, END)
password_entry.insert(0, password)

(2)save():校验 + 确认 + 追加

1
2
3
4
5
6
7
8
9
10
11
12
13
def save():
website = website_entry.get()
email = email_username_entry.get()
password = password_entry.get()

if len(password) == 0 or len(website) == 0:
messagebox.showwarning(title="Empty fields", message="Please don't leave any empty fields")
elif messagebox.askokcancel(title=website, message=f"You've entered: nEmail: {email}nPassword: {password}"
f"nIs it OK to save?"):
with open("data.txt", mode="a") as file:
file.write(f"{website} | {email} | {password}n")
website_entry.delete(0, END)
password_entry.delete(0, END)

三个要点:

  1. if / elif 而不是 if / if:校验不过就不再弹确认框。
  2. messagebox.askokcancel 返回布尔值:点「确定」是 True,点「取消」是 False。放在 elif 条件里直接判断,省一个变量。
  3. mode="a" 追加,不覆盖旧记录——这是「多条记录」的关键。换行符 n 必须手写(write 不会自动加)。

open 没有 encoding="utf-8":存纯 ASCII 密码没问题,一旦网站名有中文,Windows 上会乱码。

(3)界面布局

1
2
3
4
5
6
7
8
9
window.config(padx=25, pady=25)
canvas = Canvas(width=200, height=200)
logo_png = PhotoImage(file="logo.png")
canvas.create_image(100, 100, image=logo_png)
canvas.grid(column=1, row=0)

website_label = Label(text="Website:"); website_label.grid(column=0, row=1)
email_username_label = Label(text="Email/Username:"); email_username_label.grid(column=0, row=2)
password_label = Label(text="Password:", width=21); password_label.grid(column=0, row=3)
col 0 col 1 col 2 col 3
row 0Canvas
row 1Website:website_entry(跨 2 列)
row 2Email/Username:email_entry(跨 2 列)
row 3Password:password_entryGenerate(跨 2 列)
row 4Add(跨 2 列)

columnspan=2 让控件横跨两列:输入框占 col1–col2,按钮占 col2–col3——按钮和输入框在视觉上错开。

password_label 的 width=21:为了让「Password:」和上面两个更长的标签左对齐后宽度一致,这是一个「凑对齐」的技巧。

website_entry.focus() 让光标默认停在这个输入框,省一次点击。

email_username_entry.insert(0, "[email protected]"):预填默认邮箱(作者自己的),真实产品应该从配置读。

这份代码的问题

  1. password_entry.insert(0, ...) 不先清空:连点生成会拼接。
  2. data.txt 用 | 分隔且不转义:字段里含分隔符就废。
  3. open 没写 encoding。
  4. 明文存密码(教学代码,但必须说清)。
  5. 没有「搜索」功能:存进去就找不回来了(Day 30 补上)。
  6. if len(x) == 0 可以写 if not x。

README.md(10 行)

标题 Day 29 - Building a Password Manager GUI App with Tkinter,知识点:Working with Images and Setting up the Canvas、Use grid() and columnspan to Complete the User Interface、Saving Data to File、Dialog Boxes and Pop-Ups in Tkinter、Generate Passwords、Copy Passwords Using Pyperclip、Catch Errors and Exceptions。

七条里,Catch Errors and Exceptions 这份代码里没有(没有 try/except)——那是 Day 30 才加的。其余六条都能在代码里找到对应行。

四个文件的关系

1
2
3
logo.png ──PhotoImage──▶ Canvas
user 输入 ──get()──▶ 三个变量 ──f-string──▶ data.txt(追加)
generate ──pyperclip.copy──▶ 剪贴板 + Entry

这一天是「GUI + 文件」的最小闭环,Day 30 会在同一份界面上加 JSON 和搜索。

微信收款码 微信
支付宝收款码 支付宝
评论