Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from kivy.app import App
- from kivy.lang import Builder
- # from kivy.storage.jsonstore import JsonStore # removed, no need to use JsonStore
- from kivy.uix.boxlayout import BoxLayout
- from plyer import filechooser
- import json
- from pathlib import Path
- kv = """
- MainJson:
- orientation: 'vertical'
- padding:10
- spacing:10
- Label:
- text: 'Example of Json'
- size_hint_y: None
- height: 30
- ScrollView:
- size:self.size
- GridLayout:
- cols:2
- padding:10
- spacing:10
- height:self.minimum_height
- width:self.minimum_width
- Button:
- text:'upload photo'
- on_press:root.filechooseropenfile()
- background_color:1,1,0,1
- Image:
- source:''
- id:image1
- Label:
- text:'Name: '
- TextInput:
- multline:False
- id:name
- hint_text:'full name: '
- Label:
- text:'age'
- TextInput:
- multline:False
- id:age
- hint_text:'your Age: '
- Button:
- text:'save'
- background_color:0,0,1,1
- on_press:root.save()
- Button:
- text:'Load'
- background_color:0,1,0,1
- on_press:root.load()
- BoxLayout:
- orientation:'vertical'
- TextInput:
- id:display
- readonly:True
- Image:
- source:''
- id:simg
- """
- FILENAME = 'user_data.json'
- class MainJson(BoxLayout):
- def __init__(self, **kwargs):
- super().__init__(**kwargs)
- # self.store = JsonStore('storage.json') removed - not used
- self.p = Path(FILENAME)
- def save(self):
- dict1 = {'name': self.ids.name.text, 'age': self.ids.age.text, "image": self.ids.image1.source}
- with open(self.p, 'w') as f:
- # f.write(json.dumps(dict1, indent=4))
- json.dump(dict1, f, indent=4)
- def load(self):
- if self.p.exists():
- with open(self.p) as jn:
- d = json.load(jn) # dict is a python builtin, I changed the name to d
- self.ids.display.text = f"The saved data: Name: {d['name']}, age: {d['age']}"
- self.ids.simg.source=f"{d['image']}"
- else:
- self.ids.display.text = 'file does not exist'
- def filechooseropenfile(self):
- filechooser.open_file(on_selection=self.selected)
- def selected(self,selection):
- if selection:
- self .ids.image1.source=selection[0]
- count=1
- class JsonExampleApp(App):
- def build(self):
- return Builder.load_string(kv)
- def on_start(self):
- # load the data if it is available
- p = Path(FILENAME)
- if p.exists():
- with open(p) as jn:
- d = json.load(jn)
- # check if the file contains both name and age, if not delete the file
- if set([ 'age', 'name','image']) == d.keys():
- print('valid file, file contains the required keys')
- self.root.ids.name.text = d['name']
- self.root.ids.age.text = d['age']
- self.root.ids.age.text = d['image']
- else:
- p.unlink()
- print('invalid file deleted')
- JsonExampleApp().run()
Advertisement
Advertisement