为什么我的json文件中的所有值都被更新?

时间:2019-05-19 00:16:12

标签: python json kivy

我有一个按钮列表,按下这些按钮时,会向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
    }
}

1 个答案:

答案 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()