如何用Tkinter从TXT文件读取用户名密码实现多账户登录验证
解决Tkinter多账户登录验证问题
你的核心问题是login_data函数没有正确读取文件数据并和输入内容对比,以下是修正方案:
问题分析
原login_data存在几个关键问题:
- 循环中每次覆盖
login变量,最终仅保留文件最后一行数据 - 使用默认
split()(按空格分割),但你的数据是逗号分隔,无法正确拆分用户名和密码 - 没有获取输入框的用户名/密码,无法完成验证逻辑
- 文件打开后未手动关闭,存在资源泄漏风险
修正后的代码
1. 完善login_data验证函数
def login_data(): # 获取输入框内容并去除首尾空格 input_user = userEntry.get().strip() input_pass = passEntry.get().strip() is_valid = False # 用with语句自动管理文件生命周期 with open("saveData.txt", "r") as f: for line in f: line = line.strip() if not line: # 跳过空行 continue # 按逗号拆分存储的用户名和密码 stored_user, stored_pass = line.split(',') # 对比输入与存储数据 if stored_user.strip() == input_user and stored_pass.strip() == input_pass: is_valid = True break # 输出验证结果(可替换为弹窗提示) print("登录成功!" if is_valid else "用户名或密码错误!")
2. 优化注册函数test_function(可选)
避免写入空数据,同时用with语句保证文件安全:
def test_function(): username = userEntry.get().strip() password = passEntry.get().strip() # 校验输入是否为空 if not username or not password: print("用户名和密码不能为空!") return with open("saveData.txt", "a") as file: file.write(f"{username},{password}\n") print("账户注册成功!")
完整修改后的代码
import tkinter as tk from ctypes import windll root = tk.Tk() root.configure(background="#e7d1ff") windll.shcore.SetProcessDpiAwareness(1) def login_data(): input_user = userEntry.get().strip() input_pass = passEntry.get().strip() is_valid = False with open("saveData.txt", "r") as f: for line in f: line = line.strip() if not line: continue stored_user, stored_pass = line.split(',') if stored_user.strip() == input_user and stored_pass.strip() == input_pass: is_valid = True break print("登录成功!" if is_valid else "用户名或密码错误!") root.geometry('600x400') root.resizable(False, False) root.columnconfigure(0, weight=1) root.columnconfigure(1, weight=3) userLabel = tk.Label(root, text="Username:", font="arial 22 bold", bg="#e7d1ff") userLabel.grid(row=0, column=0, sticky=tk.E, padx=5, pady=10) userEntry = tk.Entry(root, font="helvetica 22") userEntry.grid(row=0, column=1, padx=5, pady=10) passLabel = tk.Label(root, text="Password:", font="arial 22 bold", bg="#e7d1ff") passLabel.grid(row=1, column=0, sticky=tk.E, padx=5, pady=10) passEntry = tk.Entry(root, font="helvetica 22", show="*") passEntry.grid(row=1, column=1, padx=5, pady=10) def test_function(): username = userEntry.get().strip() password = passEntry.get().strip() if not username or not password: print("用户名和密码不能为空!") return with open("saveData.txt", "a") as file: file.write(f"{username},{password}\n") print("账户注册成功!") btnLogin = tk.Button(root, text="Login", font="arial 16 bold", command=login_data) # 修正原绑定错误 btnLogin.place(relx=0.5, rely=0.4, anchor=tk.CENTER) btnTest = tk.Button(root, text="Register", font="arial 16 bold", command=test_function) # 按钮更名更贴合功能 btnTest.place(relx=0.5, rely=0.6, anchor=tk.CENTER) root.mainloop()
额外注意点
- 原代码中
btnLogin的command绑定的是test_function(注册函数),这是逻辑错误,已修正为绑定login_data - 可以把控制台打印替换为Tkinter弹窗提示(比如
tk.messagebox.showinfo),提升用户体验 - 文本文件明文存储密码存在安全风险,实际项目建议用哈希加密存储
内容的提问来源于stack exchange,提问作者Wixsy01
相关产品推荐
相关产品推荐

