omz:forum

    • Register
    • Login
    • Search
    • Recent
    • Popular

    Welcome!

    This is the community forum for my apps Pythonista and Editorial.

    For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.


    Saving Pythonista app switch and button states

    Pythonista
    5
    10
    6649
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • Vertec
      Vertec last edited by

      Assistance with saving app states.
      I am new to Pythonista and Python - How would I write the values of switches and buttons to a file and reload that file next time I open the script?

      I need an application to retain its state between loads.

      Webmaster4o 1 Reply Last reply Reply Quote 1
      • Webmaster4o
        Webmaster4o @Vertec last edited by

        @Vertec There's no built-in way to do this. You would have to manually write a file (probably JSON) each time.

        You might also be able to write to the .pyui file somehow...

        1 Reply Last reply Reply Quote 0
        • Vertec
          Vertec last edited by

          Hi, do you know how one would go about writing switch.values and button.actions to json and getting the app to write and load the Json when opening and closing ?

          1 Reply Last reply Reply Quote 0
          • JonB
            JonB last edited by

            is the user changing button actions (i.e the .action attribute)??? or just switches?

            dynamic button actions might be tricky to save, since these are references to actual objects. you would have to dave the str names and try to rebind the actions after load. better might be to have a single action, which looks at some sender attribute to decide which action to take. then, you would store the attribute, not the action, in your json.

            for switch values you would simply create a routine to traverse your view heirarchy, and store dict of switch names/values. If you have a nested view structure, you probably want a nested dict structure.

            1 Reply Last reply Reply Quote 0
            • Vertec
              Vertec last edited by

              Just switch states need to be memorised as it's easy enough to get a switch to affect a button.action and vice versa. I don't know anything about json but I've learned more about scripting in two weeks of having pythonista than ten years and five attempts with Other ides- I f$&@ing love this app.

              Oh to the point please any assistance to this code noob who took on Python because it's embedded In maya as to who is "Json" and how to communicate with him would be rewarded in ones and zeros

              Webmaster4o 1 Reply Last reply Reply Quote 0
              • JonB
                JonB last edited by

                import json
                some_string=json.dumps(some_dict)

                import json
                some_dict=json.loads(some_string)

                If you want to load/dump directly from a file, you would use json.load and json.dump. If you are using python3, you may also need to make sure your string is actually a bytes object.

                1 Reply Last reply Reply Quote 0
                • brumm
                  brumm last edited by

                  # coding: utf-8
                  import ui
                  import json
                  import os
                  
                  class RememberMe(ui.View):
                      def __init__(self):
                          self.mysettings = None
                          self.loadsettings()
                          width, height = ui.get_screen_size()
                          self.frame = (0,0,width,height)
                          self.background_color = 'white'
                          
                          self.switch1 = ui.Switch()
                          self.switch1.x = 50
                          self.switch1.y = 50
                          if self.mysettings != None:
                              value = self.mysettings.get("switch1")
                              self.switch1.value = value
                          self.add_subview(self.switch1)
                          self.present('full_screen')
                              
                      def will_close(self):
                          if self.switch1.value == True:
                              self.mysettings = {'switch1':True}
                          else:
                              self.mysettings = {'switch1':False}
                          self.savesettings()
                          
                      def loadsettings(self):
                          if os.path.exists("mysettings.json"):
                              with open("mysettings.json", "r") as f:
                                  self.mysettings = json.load(f)
                          
                      def savesettings(self):
                          with open("mysettings.json", "w") as f:
                              json.dump(self.mysettings, f)
                          
                  RememberMe()
                  
                  1 Reply Last reply Reply Quote 0
                  • Phuket2
                    Phuket2 last edited by

                    You can also consider ConfigParser. For simple values like this, is pretty easy. The file is like a windows .ini file

                    https://docs.python.org/2/library/configparser.html

                    1 Reply Last reply Reply Quote 0
                    • Webmaster4o
                      Webmaster4o @Vertec last edited by

                      @Vertec JSON is JavaScript Object Notation. From http://json.org/ :

                      JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.

                      So basically, it's a format for storing data that's supposed to be pretty human-readable.

                      It works and looks a lot like Python lists and dicts. It typically pairs keys with values like a dict, but also supports lists without keys.

                      An example JSON file taken from Wikipedia:

                      {
                        "firstName": "John",
                        "lastName": "Smith",
                        "isAlive": true,
                        "age": 25,
                        "address": {
                          "streetAddress": "21 2nd Street",
                          "city": "New York",
                          "state": "NY",
                          "postalCode": "10021-3100"
                        },
                        "phoneNumbers": [
                          {
                            "type": "home",
                            "number": "212 555-1234"
                          },
                          {
                            "type": "office",
                            "number": "646 555-4567"
                          },
                          {
                            "type": "mobile",
                            "number": "123 456-7890"
                          }
                        ],
                        "children": [],
                        "spouse": null
                      }
                      

                      As you can see it's (relatively) easy for humans to read and understand.

                      You can read more on the Wikipedia article.

                      1 Reply Last reply Reply Quote 0
                      • JonB
                        JonB last edited by JonB

                        https://github.com/jsbain/uicomponents/blob/master/ui_settings_storage.py

                        Here is a more flexible method, intended to be used with @brumm's approach. Create a custom attribute "stored" (either programmatically or in ui editor), then this method creates a dict heirarchy of all storable elements. Supports deep heirarchies, and multiple components. Ideally each component and container view has a name attribute. it will create a temporary key if it does not (but if you change the ui later, such that subviews are added in different order, it will most likely fail to restore).

                        Incidentally... json does not let you use non-string dict keys... the above approch uses yaml, which is similar, but faithfully reproduces the dicts.

                        1 Reply Last reply Reply Quote 0
                        • First post
                          Last post
                        Powered by NodeBB Forums | Contributors