Kivy - 如何在应用程序重新启动时保留稍后添加的小部件

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

我想知道是否有任何方法可以保留稍后在应用程序使用过程中添加的小部件。每当应用程序重新启动时,都会调用 build() 函数,并且在应用程序使用期间添加的小部件会消失,因为它们不是在 build() 函数中添加的。

我想在重启时保留这些小部件,就像应用程序将它们保留在暂停模式一样。

谢谢!

这里是一个使用 ini 文件和你的 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()