我正在學習如何實現(xiàn) Kivy 設置面板。這對于幾個用例來說是完美的,但我無法弄清楚如何在構(gòu)建后立即在我的應用程序中顯示設置的值。我從這里的 PalimPalims 答案中借用了這個示例代碼。更改設置時效果很好,但在更改設置面板中的值之前,標簽小部件沒有文本。text: App.get_running_app().config.get('Label','content')在將 App 導入構(gòu)建部分后,我嘗試將其添加到 kv 語言部分文本中。我還嘗試在 Apps 構(gòu)建函數(shù)中分配小部件值,但一直收到錯誤“MyApp 沒有 ids”。我必須相信這是可行的,我只是在閱讀文檔中的方法。from kivy.app import Appfrom kivy.uix.textinput import TextInputfrom kivy.uix.boxlayout import BoxLayoutfrom kivy.uix.label import Labelfrom kivy.uix.button import Buttonfrom kivy.lang import Builderfrom kivy.uix.label import Labelfrom kivy.config import Configclass Labelwithconfig(Label): def check_label(self): self.text = App.get_running_app().config.get('Label','content')kv_str = Builder.load_string("""BoxLayout: orientation: 'vertical' Labelwithconfig: id: labelconf Button: text: 'open settings' on_press: app.open_settings()""")class MyApp(App): def build_config(self, config): config.setdefaults('Label', {'Content': "Default label text"}) def build_settings(self, settings): settings.add_json_panel("StackOverflow Test Settings", self.config, data=""" [ {"type": "options", "title": "Label text System", "section": "Label", "key": "Content", "options": ["Default label text", "Other Label text"] } ]""" ) def on_config_change(self, config, section, key, value): self.root.ids.labelconf.check_label() def build(self): return kv_strif __name__ == '__main__': MyApp().run()
1 回答

蕪湖不蕪
TA貢獻1796條經(jīng)驗 獲得超7個贊
text: App.get_running_app().config.get('Label','content')當您的應用程序啟動時不會顯示您的文本,因為您的kv文件內(nèi)容在您的App類完全加載之前加載。為了做你想做的事,覆蓋類的on_start方法App(這是一個超級方便的技巧,有時新用戶很難發(fā)現(xiàn))。
def on_start(self):
self.root.ids.labelconf.text = self.config.get('Label','content')
來自 kivy 文檔:
on_start()
on_start 事件的事件處理程序,在初始化之后(在調(diào)用 build() 之后)但在應用程序開始運行之前觸發(fā)。
基本上,您可以self.whatever在build()函數(shù)完成后訪問應用程序的變量。完成on_start()時自動調(diào)用build()。
添加回答
舉報
0/150
提交
取消