在下面的代码中,我按照 kivy 文档中有关将数据存储到 JSON 文件中的说明进行操作。
我收到有关目录的错误。我更加新鲜了,我被过去的日子困住了。
错误是-->
File "main.py", line 44 data_dir = getattr(self, '/storage/emulated/0/') #获取可写路径来保存文件^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
最佳答案
在我的更新函数中,我将错误的参数传递给 json 存储。
jsonStore=('/storage/emulated/0/hello.json')
这是将 Android 设备的路径传递到 json 存储的方法
json.put('a')
它会将这个字符放入 Android 手机内部存储的 hello.json 中。
关于python - 使用 kivy 将加速度计数据存储在 json 文件中时出错。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43167554/