【问题标题】:How to loop for values in JsonStore kivy application? [duplicate]如何在 JsonStore kivy 应用程序中循环获取值? [复制]
【发布时间】:2019-09-11 18:55:08
【问题描述】:

我一直在努力寻找一种方法来使用 JsonStore 模块遍历多个对象中的一组特定值。我的代码:

class MainApp(App):

    def build(self): # build() returns an instance
        self.store = JsonStore("streak.json") # file that stores the streaks:


        return presentation

    def check_streak(self, instance):



        for value in self.store.find('delta'):

            if value > time.time():
                print("early")

            if value == time.time():
                print("on time")

            if value < time.time():
                print("late")

此功能连接到页面上显示的不同按钮:

def display_btn(self):
        # display the names of the streaks in a list on PageTwo
        for key in self.store:
            streak_button = Button(text=key, on_press=self.check_streak)
            self.root.screen_two.ids.streak_zone.add_widget(streak_button)

当我使用 check_streak 时,我得到TypeError: find() takes 1 positional argument but 2 were given

json 文件里面有什么:

{"first": {"action": "first", "action_num": "1", "seconds": 60, "score": 0, "delta": 1555714261.0438898}, "second": {"action": "second", "action_num": "2", "seconds": 120, "score": 0, "delta": 1555879741.894656}}

请注意,每个对象都以其名称开头,在本例中为“first”和“second”。我希望能够遍历每个对象的“delta”键并获得它的值。一旦我得到那个对象'delta'的值,我就会将它与当前时间进行比较。

我被提到了一个涉及生成 id 的问题,但我不明白这与我的问题有什么关系。虽然我认为生成器有利于创建随机数,但我正在使用的数据不是随机的。如果使用生成器是做我想做的事情的唯一方法,有人可以向我解释如何在我的代码中使用它吗?

我之前收到的答案并没有说明我希望“delta”值仍然附加到对象而不是仅仅列出它们。

【问题讨论】:

  • 从文档看来,self.store.find 需要一个或多个关键字参数,可能类似于 for value in self.store.find(delta='somevalue')。这也是错误的意思:函数根本不期望位置参数。
  • 创建新问题不依赖于您收到的答案,如果是相同的问题是重复的,并且创建具有相同问题的新出版物在这里被认为是噪音。

标签: python kivy jsonstore


【解决方案1】:

如何使用recursive iteration through nested json for specific key in python

以下示例不使用JsonStore。它使用json.load 加载JSON 对象。

片段

import json
...
    def check_streak(self, *args):
        with open("streak.json", "r") as read_file:
            data = json.load(read_file)

            for honey in item_generator(data, 'delta'):
                print(f"honey={honey}")
                print(f"type(honey)={type(honey)}")

                if honey > time.time():
                    print("early")  # test

                if honey == time.time():
                    print("on time")

                if honey < time.time():
                    print("late")

注意

store.find(key='value') 函数无法使用,因为delta 不是固定的或恒定的。不像name='kivy'

【讨论】:

  • 谢谢!这与已经回答的问题一起提供了帮助。很抱歉创建了一个重复的问题,我只是有一段时间没看懂生成器代码。
猜你喜欢
  • 2022-11-29
  • 2014-10-12
  • 2019-06-04
  • 2014-12-06
  • 2023-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
相关资源
最近更新 更多