我已将我的注册详细信息保存在csv文件中,登录时我想验证数据是否有效.但我面对的是错误



保存注册详情

#将注册详细信息保存到字典中并显示确认消息

def save_sign_up():
forename = forename_text.get()
dob = dob_text.get()
username = username_text.get()
password = password_text.get()
# Save the login details to a CSV file
with open("sign_up.csv", "a") as writer:
writer.write(f"{forename}, {dob}, {username}, {password}n")
sign_up_window.destroy()

保存登录详情

#将登录详情保存为CSV文件的功能

def save_login():
username = username_text.get()
password = password_text.get()
# opening the CSV file
with open('sign_up.csv', mode='r') as file:
# reading the CSV file
cfile = csv.DictReader(file)
# check if the username and password are valid
for row in cfile:
if username == row['username'] and password == row['password']:
review_label.config(text="Login successful!")
# Close the login window
login_window.destroy()
break
else:
review_label.config(text="Invalid username or password. Please try again.")
# Close the login window
login_window.destroy()

错误
Exception in Tkinter callback
Traceback (most recent call last):
File "#", line 1948, in __call__
return self.func(*args)
^^^^^^^^^^^^^^^^
File "#", line 52, in save_login
if username == row['username'] and password == row['password']:
~~~^^^^^^^^^^^^
KeyError: 'username'

你的代码中有几个问题:

  • 您需要在CSV文件的开头添加标题行(用作密钥),或者在创建csv.DictReader()

    时传递密钥
  • CSV文件的每行逗号后面有额外的空格

  • else块应与save_login()块内的for块相同

更新后的代码:

def save_sign_up():
forename = forename_text.get()
dob = dob_text.get()
username = username_text.get()
password = password_text.get()
# Save the login details to a CSV file
with open("sign_up.csv", "a") as writer:
# removed extra space after the commas
writer.write(f"{forename},{dob},{username},{password}n")
sign_up_window.destroy()
def save_login():
username = username_text.get()
password = password_text.get()
# opening the CSV file
with open('sign_up.csv', mode='r') as file:
# reading the CSV file
# provide the keys when creating the reader
cfile = csv.DictReader(file, ('forename', 'dob', 'username', 'password'))
# check if the username and password are valid
for row in cfile:
if username == row['username'] and password == row['password']:
review_label.config(text="Login successful!")
# Close the login window
#login_window.destroy()  # will be called after the for loop
break
else:   # same indentation as for
review_label.config(text="Invalid username or password. Please try again.")
# Close the login window
login_window.destroy()   # should it be called actually?

相关内容

  • 没有找到相关文章

最新更新