我和我的 friend 正在制作一个需要在开始时登录的程序。我们设法让用户输入详细信息,并让程序创建一个名为(用户名)配置文件的文本文件,其中包含详细信息。每个文件的格式如下:
(姓名)
(用户名)
(密码)
当您想登录时,程序会询问您的姓名并找到名称为(无论他们输入什么)配置文件的文件。 如果它存在,程序会打开一个 GUI 窗口并询问用户名和密码,如果你为它打开的文件输入正确的详细信息,它会说详细信息是错误的。我们认为它与变量有关,但我们已经尝试了很多不同的方式来布置它等,但找不到问题所在。谁能帮忙? (我包含的代码只是 GUI 部分,包括不起作用的部分,其余都很好。
# Log in
def LogIn():
name=input("Please enter your name: ")
file = open(name.lower() + " profile.txt", "r")
#+=========GUI===========GUI============GUI===========+
#mport modules
import tkinter
import time
#---Window---#
#make window
window = tkinter.Tk()
#change title
window.title("Python Games Login")
#change size
window.geometry("270x210")
#change window icon
window.wm_iconbitmap("Login icon.ico")
#change window colour
window.configure(bg="#39d972")
#---Commands---#
#go
def callback():
line = file.readlines()
username = user.get()
password = passw.get()
if username == line[1] and password == line[2]:
message.configure(text = "Logged in.")
else:
message.configure(text = "Username and password don't match the account \n under the name;\n \'" + name + "\'. \nPlease try again.")
#---Widgets---#
#labels
title1 = tkinter.Label(window, text="--Log in to play the Python Games--\n", bg="#39d972")
usertitle = tkinter.Label(window, text="---Username---", bg="#39d972")
passtitle = tkinter.Label(window, text="---Password---", bg="#39d972")
message = tkinter.Label(window, bg="#39d972")
#text entry windows
user = tkinter.Entry(window)
passw = tkinter.Entry(window, show='*')
#buttons
go = tkinter.Button(window, text="Log in!", command = callback, bg="#93ff00")
#pack widgets
title1.pack()
usertitle.pack()
user.pack()
passtitle.pack()
passw.pack()
go.pack()
message.pack()
#start window
window.mainloop()
#+===================GUI END=====================+
最佳答案
我会使用 python 的 pickle 模块来保存数据。它比仅将其保存在文本文件中要高级得多。在我的示例中,我选择了字典列表。
import pickle
def LogIn():
name=input("Please enter your name: ").lower()
#data.pickle should be a list of dictionaries representing a user
usernames= pickle.load('data.pickle')
for userdata in usernames:
if userdata['name']== name:
return userdata
#didn't find the name
print('could not find '+ name+ ' in data.pickle')
return None
来自 the docs 的关于pickle 的注释:
Warning:
The pickle module is not intended to be secure against erroneous or maliciously constructed data. Never unpickle data received from an untrusted or unauthenticated source.
同时查看shelve和marshal,它们执行类似的结果,或者考虑将其保存为json文件格式(python有一个json模块)
关于Python GUI登录程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22269625/