繁体   English   中英

如何在tkinter中创建密码系统以从文件中读取数据

[英]How to create password system in tkinter reading the data from file

我想用记事本作为数据库在tkinter中创建密码系统,该数据库包含我的工作目录中的数据,但是当我在输入字段中插入数据时,我收到一个错误的登录失败。创建了txt文件,但该功能似乎无法从文件中读取任何有关此操作的建议。

import tkinter as tk
import sys
from tkinter import messagebox


now = open("passdoc.txt","w+")
now.write("user\n")
now.write("python3")
now.close()

def login_in():
    with open("passdoc.txt") as f:
        new = f.readlines()
        name = new[0].rstrip()
        password = new[1].rstrip()
    if entry1.get() == new[0] in passdoc.txt and entry2.get() == new[1] in 
passdoc.txt:
        root.deiconify()
        log.destroy()
    else:
        messagebox.showerror("error","login Failed")


def close():
    log.destroy() #Removes toplevel window
    root.destroy() #Removes  root window
    sys.exit() #Ends the script


root=tk.Tk()
log = tk.Toplevel() #

root.geometry("350x350")
log.geometry("200x200")

entry1 = tk.Entry(log) #Username entry
entry2 = tk.Entry(log) #Password entry
button1 = tk.Button(log, text="Login", command=login_in) #Login button
button2 = tk.Button(log, text="Cancel", command=close) #Cancel button
label1 = tk.Label(root, text="tkinter password system")

entry1.pack()
entry2.pack()
button1.pack()
button2.pack()
label1.place(x=30,y=300)


label = tk.Label(root, text="welcome").pack()

root.withdraw()
root.mainloop()

我也创建了这个函数,但是似乎所有的东西都不适合我

def login_in():
    with open("passdoc.txt") as f:
        new = f.readlines()
        name = new[0].rstrip()
        password = new[1].rstrip()
    if entry1.get() == name in passdoc.txt and entry2.get() == password in 
passdoc.txt:
        root.deiconify()
        log.destroy()
    else:
        messagebox.showerror("errror","login failed")    #error login failed 
(corrections)

您的代码中有几件事需要做一些工作,但主要问题是您的login_in()函数。

您的if陈述全错了。 我不确定为什么您会像以前那样编写它,但让我们对其进行修复。

因为您定义了name = new[0].rstrip()password = new[1].rstrip() ,所以可以使用namepassword来验证用户是否输入了正确的凭据。

因此,您的if语句应如下所示:

if entry1.get() == name and entry2.get() == password:

您对in passdoc.txt使用没有任何作用,也无法正常工作,因为将python的passdoc.txt看起来像是未定义的变量,并且在if语句上会失败。 请记住,您将passdoc.txt所有内容都passdoc.txtf因此没有创建名为passdoc的变量, passdocwith open()语句的名为f的变量创建了一个变量。

如果您想稍微缩短代码,则可以删除namepassword变量,而只需在if语句中输入new

因此,您的login_in()函数可能如下所示:

def login_in():
    with open("passdoc.txt") as f:
        new = f.readlines()
        name = new[0].rstrip()
        password = new[1].rstrip()
    if entry1.get() == name and entry2.get() == password:
        root.deiconify()
        log.destroy()
    else:
        messagebox.showerror("error","login Failed")

或这个:

def login_in():
    with open("passdoc.txt") as f:
        new = f.readlines()
    if entry1.get() == new[0].rstrip() and entry2.get() == new[1].rstrip():
        root.deiconify()
        log.destroy()
    else:
        messagebox.showerror("error","login Failed")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM