保存注册详情
#将注册详细信息保存到字典中并显示确认消息
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?