【发布时间】:2019-05-24 23:49:43
【问题描述】:
我的 json 文件中有连接到键的按钮。使用 kivy 的时钟模块,我检查连接到按钮的值并更改其颜色。当按钮变为红色时,我希望它的 score 值变为 0 并存储在 json 文件中。当我在 json 文件中保存了多个按钮时,分数不会变为零,直到我按下一个按钮,当我按下按钮时,除了第一个按钮之外的所有值都变为 0,这不是我想要的。
class MainApp(App):
def build(self): # build() returns an instance
self.store = JsonStore("streak.json") # file that stores the streaks:
Clock.schedule_interval(self.check_streak, 1 / 30.)
return presentation
def check_streak(self, dt):
for child in reversed(self.root.screen_two.ids.streak_zone.children):
name = child.text
with open("streak.json", "r") as read_file:
data = json.load(read_file)
for key in data.keys():
if key == name:
delay = data.get(key, {}).get('delay') # get value of nested key 'delay'
self.honey = data[key]['delta']
float(self.honey)
if delay > time.time() < self.honey: # early (yellow)
child.background_normal = ''
child.background_color = [1, 1, 0, 1]
child.unbind(on_press=self.add_score)
child.bind(on_press=self.early_click)
elif delay > time.time() > self.honey: # on time (green)
child.background_normal = ''
child.background_color = [0, 1, 0, 1]
child.unbind(on_press=self.early_click)
child.bind(on_press=self.add_score)
elif delay < time.time() > self.honey: # late (red)
child.background_normal = ''
child.background_color = [1, 0, 0, 1]
child.unbind(on_press=self.add_score)
child.unbind(on_press=self.early_click)
with open("streak.json", "r+") as f:
files = json.load(f)
files[child.text]['score'] = 0
f.seek(0)
json.dump(files, f, indent=4)
f.truncate()
json 文件:
{
"One": {
"action": "One",
"delay": 1558740875.58999,
"seconds": 60,
"score": 3,
"delta": 1558740815.58999,
"grace_sec": 120
},
"Two": {
"action": "Two",
"delay": 1558740752.0085213,
"seconds": 60,
"score": 0,
"delta": 1558740692.0085213,
"grace_sec": 120
},
"Three": {
"action": "Three",
"delay": 1558746820.4364505,
"seconds": 60,
"score": 0,
"delta": 1558740820.4364505,
"grace_sec": 6060
}
}
我只希望红色按钮将其 score 更改为 0,但 Two 和 Three 都会更改,即使只有 Two 是红色的。此外,只有当我按下绿色按钮时,分数才会改变,在这种情况下,它是One。这不是我想要的。我希望分数使用时钟模块更新自己。
【问题讨论】:
标签: json python-3.x kivy