Kivy - How to keep widgets that are added later when the app restarts

放肆的年华 提交于 2021-01-29 07:12:59

问题


I was wondering if there is any way to keep widgets that are added later during the application use. Whenever the app restarts, the build() function is called, and the widgets that have been added during the app usage disappear since they were not added in build() function.

I want to keep these widgets in the restart in the same way the app keeps them in Pause mode.

Thank you!


回答1:


Here is a simple example of using an ini file with your Kivy App:

import os
import ast

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label


kv = '''
BoxLayout:
    orientation: 'vertical'
    BoxLayout:
        orientation: 'horizontal'
        size_hint_y: 0.15
        Button:
            text: 'Add Widget'
            on_release: app.do_add()
        Button:
            text: 'Some Button'
        Button:
            text: 'Another Button'
    BoxLayout:
        size_hint_y: 0.85
        orientation: 'vertical'
        id: box
'''


class TestApp(App):
    def build(self):
        self.count = 0  # counter used in Label text
        return Builder.load_string(kv)

    def build_config(self, config):
        # Make sure that the config has at least default entries that we need
        config.setdefaults('app', {
            'labels': '[]',
        })

    def get_application_config(self):
        # This defines the path and name where the ini file is located
        return str(os.path.join(os.path.expanduser('~'), 'TestApp.ini'))

    def on_start(self):
        # the ini file is read automatically, here we initiate doing something with it
        self.load_my_config()

    def on_stop(self):
        # save the config when the app exits
        self.save_config()

    def do_add(self):
        self.count += 1
        self.root.ids.box.add_widget(Label(text='Label ' + str(self.count)))

    def save_config(self):
        # this writes the data we want to save to the config
        labels = []
        for wid in self.root.ids.box.children:
            labels.append(wid.text)

        # set the data in the config
        self.config.set('app', 'labels', str(labels))

        # write the config file
        self.config.write()

    def load_my_config(self):
        # extract our saved data from the config (it has already been read)
        labels_str = self.config.get('app', 'labels')

        # us the extracted data to build the Labels
        labels = ast.literal_eval(labels_str)
        labels.reverse()
        self.count = len(labels)
        for lab in labels:
            self.root.ids.box.add_widget(Label(text=lab))


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


来源:https://stackoverflow.com/questions/63226179/kivy-how-to-keep-widgets-that-are-added-later-when-the-app-restarts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!