我有一些按钮连接到json文件中的键。使用kivy的Clock模块,我检查连接到按钮的值并更改其颜色。当按钮变成红色时,我希望它的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
。这不是我想要的。我希望乐谱使用“时钟”模块更新其自我。
答案 0 :(得分:0)
案例1:我认为time.time()总是对延迟和蜜月都更大,并且每次进入第三条件并将得分设置为零。
另一个选项:只需跟踪列表中所有红色按钮,然后对其进行迭代并立即更新json文件。
答案 1 :(得分:0)
创建了一个单独的函数,该函数使用时钟来更新json文件。
# change score to 0 and stores in json file
def score_gone(self, dt):
for child in self.root.screen_two.ids.streak_zone.children:
name = child.text
color = child.background_color
with open("streak.json", "r") as file:
read = json.load(file)
if color == [1, 0, 0, .95]: # red
if read[name]['score'] != 0: #stops slow down from Clock
with open("streak.json", "r+") as f: # fix score not reseting to 0
data = json.load(f)
data[name]['score'] = 0
f.seek(0)
json.dump(data, f, indent=4)
f.truncate()
elif read[name]['score'] == 0: #stops slow down from Clock
pass