以kivy保存值

时间:2015-08-08 19:50:52

标签: android python kivy

我写了一个小型的kivy程序,因为我想学习如何使用.json文件保存值。 我检查了文档,发现了这个:http://kivy.org/docs/api-kivy.storage.html#module-kivy.storage 我尝试了类似的,但我得到了错误:ImportError: No module named storage.jsonstore

为什么它不起作用?

这是我的代码:

from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.storage.jsonstore import JsonStore
from kivy.properties import StringProperty
from kivy.properties import NumericProperty
from kivy.uix.scrollview import ScrollView
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout


class Layout(BoxLayout):
    def save(self, vinput):
        store = JsonStore('hello.json')
        store.put('tito', inpud=vinput)

ROOT = Builder.load_string('''
BoxLayout:
    orientation: 'vertical'
    TextInput:
        id:my_textinput
    Button:
        text: 'save'
    Button:
        text: 'acsess'

''')


class Caption(App):
    def build(self):
        Window.clearcolor = (0, 0, 1, 1)
        return ROOT

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

1 个答案:

答案 0 :(得分:1)

我之前从未使用过JsonStore,我会看看它,然后会更新答案,但就目前而言,你可以这样做。

import json

#If you want to write in your JSON file.
out_file = open("your_file.json","w")
json.dump(result,out_file, indent=4)
   # result ^ contains your data.
   # indent = 4 is to make your file more readable.
out_file.close()

#If you want to read your JSON file.

in_file = open("your_file.json","r")
result = json.load(in_file)
in_file.close()

编辑:1

它实际上非常好。 试试这个改进的代码。

您的.py文件

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

class Lay_out(BoxLayout):
    def save(self, vinput):
        store = JsonStore('hello.json')
        store.put('tito', inpud=vinput)

class CaptionApp(App):
    def build(self):
        return Lay_out()

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

您的.kv文件

<Lay_out>:
    orientation: 'vertical'
    TextInput:
        id:my_textinput
    Button:
        text: 'save'
        on_release: root.save(my_textinput.text)
    Button:
        text: 'acsess'