Kivy-如何保留在应用程序重启时稍后添加的小部件 [英] Kivy - How to keep widgets that are added later when the app restarts
本文介绍了Kivy-如何保留在应用程序重启时稍后添加的小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有任何方法可以保留在应用程序使用期间稍后添加的小部件.每当应用程序重新启动时,都会调用build()函数,并且在应用程序使用过程中添加的小部件会消失,因为它们未添加到build()函数中.
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.
谢谢!
推荐答案
以下是将ini
文件与Kivy App
一起使用的简单示例:
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()
这篇关于Kivy-如何保留在应用程序重启时稍后添加的小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文