我有一个按钮列表,按下这些按钮时,会向score
添加1的值。该按钮被视为screen_two.ids.streak_zone
的子级。当我按下按钮时,它将为json文件中的所有按钮更新score
的值。如何使其仅更新一个按钮?
这里是我的代码:
def add_score(self, obj):
for child in reversed(self.root.screen_two.ids.streak_zone.children):
name = child.text
with open("streak.json", "r") as file:
read = json.load(file)
for key in read.keys():
if key == name:
with open("streak.json", "r+") as f:
data = json.load(f)
data[key]['score']+=1
f.seek(0)
json.dump(data, f, indent=4)
f.truncate()
json文件:
{
"one": {
"action": "one",
"delay": 1558824388.0762293,
"seconds": 60,
"score": 5,
"delta": 1558224388.0762293
},
"two": {
"action": "two",
"delay": 1558824393.8408294,
"seconds": 60,
"score": 5,
"delta": 1558224393.8408294
}
}
答案 0 :(得分:0)
删除了子循环,并制作了name = obj.text
代码:
def add_score(self, obj):
name = obj.text
with open("streak.json", "r") as file:
read = json.load(file)
for key in read.keys():
if key == name:
with open("streak.json", "r+") as f:
data = json.load(f)
data[key]['score']+=1
f.seek(0)
json.dump(data, f, indent=4)
f.truncate()