使用kivy将加速度计数据存储在json文件中时出错。

时间:2017-04-02 11:05:19

标签: python json python-2.7 kivy

在下面的代码中,我根据kivy文档关于将数据存储到JSON文件中的说明 我收到有关目录的错误。我比较新鲜,过去几天我都被困住了 错误是 - >

文件" main.py",第44行data_dir = getattr(self,' / storage / emulated / 0 /')#get一个可写路径来保存文件^ IndentationError :意外缩进

__version__ = '1.0' #declare the app version. Will be used by buildozer


from kivy.app import App #for the main app
from kivy.uix.floatlayout import FloatLayout #the UI layout
from kivy.uix.label import Label #a label to show information
from plyer import accelerometer #object to read the accelerometer
from kivy.clock import Clock #clock to schedule a method
from kivy.storage.jsonstore import JsonStore
from os.path import join

class UI(FloatLayout):#the app ui
    def __init__(self, **kwargs):
        super(UI, self).__init__(**kwargs)
        self.lblAcce = Label(text="Accelerometer: ") #create a label at the                   center
        self.add_widget(self.lblAcce) #add the label at the screen

        try:

            accelerometer.enable() #enable the accelerometer
            # if you want do disable it, just run: accelerometer.disable()
            Clock.schedule_interval(self.update, 2.0/1) #24 calls per second
        except:
            self.lblAcce.text = "Failed to start accelerometer" #error

    def update(self, dt):
        txt = ""
        try:
            txt = "Accelerometer:\nX = %.2f\nY = %.2f\nZ = %2.f " %(
              accelerometer.acceleration[0], #read the X value
              accelerometer.acceleration[1], # Y
              accelerometer.acceleration[2]) # Z

            data_dir = getattr(self, '/storage/emulated/0/') #get a writable path to save the file
            store = JsonStore(join(data_dir, 'user.json'))   

            store.put('x',accelerometer.acceleration[0])
            store.put('y',accelerometer.acceleration[1])
            store.put('z',accelerometer.acceleration[2])
        except:
            txt = "Cannot read accelerometer!" #error
        self.lblAcce.text = txt #add the correct text 

class Accelerometer(App): #our app
    def build(self):
        ui = UI()# create the UI
        return ui #show it

if __name__ == '__main__':
    Accelerometer().run() #start our app

1 个答案:

答案 0 :(得分:1)

在我的更新功能中,我将错误的arrguemnts传递给json商店。

json.put('a')

这是将Android设备的路径传递给json商店的方法

#define Center(x) CGPointMake(CGRectGetMidX(x), CGRectGetMidY(x));

它将把这个角色放在hello.json的android mobile的内部存储中。