【问题标题】:save variables in kivy android with JsonStore使用 JsonStore 在 kivy android 中保存变量
【发布时间】:2017-12-29 05:02:52
【问题描述】:

我想在 kivy 中为 android 应用程序保存一个变量(label.text),当应用程序重新启动时,它应该将变量加载回 label.text。

我尝试使用JsonStore来保存变量https://kivy.org/docs/api-kivy.storage.html#

有没有更好的方法来保存变量?

但是当我运行代码时出现以下错误:

ValueError: 无法解码 JSON 对象

这是我的 ma​​in.py 文件:

from kivy.app import App
from kivy.storage.jsonstore import JsonStore
from kivy.uix.boxlayout import BoxLayout
from kivy.core.window import Window


class Test(BoxLayout):
    Window.clearcolor = (1, 1, 1, 1)
    def save(self):
        store = JsonStore('hello.json')
        store.put('tito', score=label.text)

class MyApp(App):
    def build(self):
        return Test()
    def on_start(self):
        store = JsonStore('hello.json')
        label.text = store.get('tito')['score']


if __name__ == '__main__':
    MyApp().run()

这是我的 my.kv 文件:

<Test>:
    orientation: "vertical"
    BoxLayout:
        Label:
            id: label
            text: '0'
            color: 0,0,0,1
            pos: 250,200
            size: 50,50
            font_size:30
        Button:
            text: 'save'
            on_release: root.save()
        Button:
            text: 'load'
            on_release:

    Button:
        size_hint: 1, .5
        text: 'click me'
        on_press: label.text = str(int(label.text)+1)

这里是完整的错误信息:

 Traceback (most recent call last):
   File "main.py", line 25, in <module>
     MyApp().run()
   File "/usr/lib/python2.7/dist-packages/kivy/app.py", line 823, in run
     self.dispatch('on_start')
   File "kivy/_event.pyx", line 699, in kivy._event.EventDispatcher.dispatch (kivy/_event.c:7394)
   File "main.py", line 20, in on_start
     store = JsonStore('hello.json')
   File "/usr/lib/python2.7/dist-packages/kivy/storage/jsonstore.py", line 25, in __init__
     super(JsonStore, self).__init__(**kwargs)
   File "/usr/lib/python2.7/dist-packages/kivy/storage/__init__.py", line 133, in __init__
     self.store_load()
   File "/usr/lib/python2.7/dist-packages/kivy/storage/jsonstore.py", line 34, in store_load
     self._data = loads(data)
   File "/usr/lib/python2.7/json/__init__.py", line 339, in loads
     return _default_decoder.decode(s)
   File "/usr/lib/python2.7/json/decoder.py", line 364, in decode
     obj, end = self.raw_decode(s, idx=_w(s, 0).end())
   File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode
     raise ValueError("No JSON object could be decoded")
 ValueError: No JSON object could be decoded

提前致谢

【问题讨论】:

    标签: android python json kivy


    【解决方案1】:

    错误有点笼统,但您的 JSON 似乎无效。您的 JSON 应该类似于:

    {"tito": {"score": "3"}}
    

    您可以在Test 类中使用__init__ 方法在启动时加载Json,我认为在这种情况下它比使用on_start 方法最简单。

    另一方面,您需要先测试 JSON 文件和密钥是否存在,然后再尝试获取它。否则,您可以提出 KeyError 异常。你可以使用 try-except 。

    from kivy.app import App
    from kivy.storage.jsonstore import JsonStore
    from kivy.uix.boxlayout import BoxLayout
    from kivy.core.window import Window
    from kivy.lang import Builder
    from kivy.properties import ObjectProperty
    
    kv_text = '''\
    <Test>:
        orientation: "vertical"
        label: label
        BoxLayout:
            Label:
                id: label
                text: '0'
                color: 0,0,0,1
                pos: 250,200
                size: 50,50
                font_size:30
            Button:
                text: 'save'
                on_release: root.save()
            Button:
                text: 'load'
                on_release: root.load()
    
        Button:
            size_hint: 1, .5
            text: 'click me'
            on_press: label.text = str(int(label.text)+1)
    '''
    
    class Test(BoxLayout):
        label = ObjectProperty()
        Window.clearcolor = (1, 1, 1, 1)
    
        def __init__(self, **kwargs):
            super(Test,  self).__init__(**kwargs)
            self.store = JsonStore('hello.json')
            self.load()
    
        def save(self):
            self.store.put('tito', score= self.label.text)
    
        def load(self):
            try:
                self.label.text = self.store.get('tito')['score']
            except KeyError:
                pass
    
    
    class MyApp(App):
        def build(self):
            Builder.load_string(kv_text)
            return Test()
    
    
    if __name__ == '__main__':
        MyApp().run()
    

    【讨论】:

      猜你喜欢
      • 2019-06-04
      • 2015-06-18
      • 2020-05-12
      • 2014-12-05
      • 1970-01-01
      • 1970-01-01
      • 2014-10-26
      • 2014-11-20
      • 2015-01-08
      相关资源
      最近更新 更多