我如何使用 tkinter 从 .txt 文件读取用户名和密码

问题描述 投票:0回答:1

我对 python 还算陌生,试图使用 tkinter 制作一个基本的登录页面,并在文本文件中读取和写入数据,以便拥有多个“帐户”。我能够以“a,b”格式写入数据 ”,然后我尝试读取数据作为用户名和密码来验证登录,再次使用多个帐户。

这是我的程序:

import tkinter as tk

from ctypes import windll

root = tk.Tk()
root.title("Log-in Page")
root.configure(background = "#e7d1ff")
windll.shcore.SetProcessDpiAwareness(1)

def login_data():
    for file in open("saveData.txt", "r").readlines():
        login = file.split()
    print(login)

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():
    file = open("saveData.txt", "a")
    user_info = str(userEntry.get() + "," + str(passEntry.get() + "\n"))
    file.write(user_info)
    file.close()

btnLogin = tk.Button(root, text="Login", font="arial 16 bold", command = test_function)
btnLogin.place(relx=0.5, rely=0.4, anchor=tk.CENTER)

btnTest = tk.Button(root, text="Test", font="arial 16 bold", command = login_data)
your textbtnTest.place (relx=0.5, rely=0.6, anchor=tk.CENTER)

root.mainloop()

我陷入了login_data 函数。我怎样才能做到这一点?

python authentication tkinter txt
1个回答
0
投票
 import tkinter as tk
from tkinter import messagebox
from ctypes import windll

root = tk.Tk()
root.title("Log-in Page")
root.configure(background="#e7d1ff")
windll.shcore.SetProcessDpiAwareness(1)

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 register_user():
    username = userEntry.get()
    password = passEntry.get()

    if not username or not password:
        messagebox.showerror("Error", "Please enter both username and password.")
        return

    try:
        with open("saveData.txt", "r") as f:
            for line in f:
                line = line.strip()
                if line:
                    stored_username, _ = line.split(",")
                    if username == stored_username:
                        messagebox.showerror("Registration Error", "Username already exists.")
                        return
    except FileNotFoundError:
        pass 

    with open("saveData.txt", "a") as file:
        file.write(f"{username},{password}\n")

    messagebox.showinfo("Registration", "User registered successfully!")
    userEntry.delete(0, tk.END)
    passEntry.delete(0, tk.END)

def login_data():
    username = userEntry.get()
    password = passEntry.get()

    if not username or not password:
        messagebox.showerror("Error", "Please enter both username and password.")
        return

    try:
        with open("saveData.txt", "r") as f:
            for line in f:
                line = line.strip()
                if line:
                    stored_username, stored_password = line.split(",")
                    if username == stored_username and password == stored_password:
                        messagebox.showinfo("Login", "Login successful!")
                        userEntry.delete(0, tk.END)
                        passEntry.delete(0, tk.END)
                        return
        messagebox.showerror("Login", "Login failed! Invalid username or password.")
    except FileNotFoundError:
        messagebox.showerror("Error", "No users found. Please register first.")

btnLogin = tk.Button(root, text="Login", font="arial 16 bold", command=login_data)
btnLogin.place(relx=0.5, rely=0.4, anchor=tk.CENTER)

btnRegister = tk.Button(root, text="Register", font="arial 16 bold", command=register_user)
btnRegister.place(relx=0.5, rely=0.6, anchor=tk.CENTER)

root.mainloop()
  • 您使用
    file
    作为循环中的变量和内置函数
    open("saveData.txt", "r")
    。这可能会引起混乱。
  • 您无法从输入字段中检索用户名和密码。
  • 用户输入和存储的凭据之间没有比较。
  • 您的
    test_function
    实际上正在注册用户(写入文件),但它与“登录”按钮相关联。
  • 您的
    login_data
    函数应该处理登录,但不执行必要的检查。
© www.soinside.com 2019 - 2024. All rights reserved.