If 语句检查变量的值是否在 JSON 文件中 [英] If statement to check if the value of a variable is in a JSON file
问题描述
我是个新手,所以尽量不要评判我.我正在尝试基于旧的 2d 马里奥创建一个小的 2d 游戏.我已经有主窗口、注册和登录窗口,而且我有一个 json 文件来保存用户名和密码.现在,我正在尝试使登录功能正常工作.问题似乎是这一行:
I'm kind of new so try not to judge me. I'm trying to create a little 2d game based on the old 2d Mario. I already have home window, the sign up and login windows, and I've got a json file to save the usernames and passwords. Now, I'm trying to get the login function to work. The problem seems to be this line:
if plpaword in players['password']
这应该可以帮助你理解变量代表什么
This should help you understand what the variables stand for
f = open('player.json')
players = json.load(f)
plpaword = E2.get()
当我运行我的代码时,在我尝试登录之前,其他一切似乎都可以正常工作.登录后,它应该创建一个新窗口,但是什么也没有发生,它给出了错误:
When I run my code, everything else seems to work fine until I try to log in. After logging in, it should create a new window, but what happens is nothing happens and it gives the error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/__init__.py", line 1883, in __call__
return self.func(*args)
File "/Users/kevin/PycharmProjects/ANewFile/ANewFile.py", line 101, in LI
passwords = players['password']
KeyError: 'password'
我使用了这些模块:
from tkinter import *
import tkinter
import tkinter.messagebox
from tkinter import messagebox
from tkinter import Tk, Button, Frame, Entry, END
import random
import json
创建一个帐户并将其保存到我的 player.json 文件中:
Creating an account and saving it to my player.json file:
def SU():
try:
plusname = E1.get()
plpaword = E2.get()
plpaword2 = E3.get()
plemail = E4.get()
if plpaword == plpaword2:
if plusname in players:
messagebox.showerror(random.choice(error), "An account with that username already exists. "
"Please choose another.")
else:
players[plusname] = {'password': plpaword, 'email': plemail}
with open('player.json', 'w') as f:
json.dump(players, f)
signup.destroy()
messagebox.showinfo("Account Created!", "Please log in to your new account through log in.")
else:
messagebox.showerror(random.choice(error), "Passwords did not match. Please try again")
except:
messagebox.showerror(random.choice(error), random.choice(errormsg))
推荐答案
根据SU()
的代码,JSON文件里面的内容(也是players的内容
代码>) 应该如下所示:
According to the code of SU()
, the content inside the JSON file (also the content of players
) should be something like below:
{
"user1": {"password": "pass1", "email": "user1@email.com"},
"user2": {"password": "pass2", "email": "user2@email.com"}
}
所以检查应该是:
plusname = E1.get()
plpaword = E2.get()
for player in players:
if plusname == player and plpaword == players[plusname]["password"]:
print("login successful")
break
else:
print("login failed")
即 players[password"]
应该是 players[plusname][password"]
.
这篇关于If 语句检查变量的值是否在 JSON 文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!