有沒有辦法從 py 文件引用自定義小部件?我在kv中制作了一個小部件,但我想從py引用它,然后將其再次添加到kv中的另一個小部件中。我嘗試使用 id 執(zhí)行此操作,但出現(xiàn)錯誤 ( KeyError: 'words_entry')。這是我嘗試過的:from kivy.app import Appfrom kivy.uix.screenmanager import ScreenManager, Screenfrom kivy.lang import Builderfrom kivy.properties import ObjectPropertyfrom kivy.uix.textinput import TextInputimport osclass GetCount(Screen): count_input = ObjectProperty(None) def next(self): # Setup next screen text_inputs = [self.ids.words_entry for i in range(int(self.count_input.text))] for text_input in text_inputs: self.manager.ids.get_input.ids.grid.add_widget(text_input) # Switch to next screen self.manager.current = "get_input"class GetInput(Screen): passkv_file = Builder.load_string("""ScreenManager: GetCount: name: "get_count" id: get_count GetInput: name: "get_input" id: get_input<WordEntry@TextInput>: id: words_entry multiline: False size_hint: (self.width, None)<GetCount>: count_input: count_input FloatLayout: Label: text: "count" size_hint: 1, 0.05 pos_hint: {"top":0.9} TextInput: id: count_input size_hint: 0.8, 0.05 pos_hint: {"top":0.7, "x":0.1} multiline: False Button: text: "Next" on_release: root.next() size_hint: 0.8, 0.05 pos_hint: {"top":0.5, "x":0.1}<GetInput>: ScrollView: GridLayout: size_hint_y: None height: self.minimum_height id: grid cols: 1""")class MainApp(App): def build(self): return kv_fileif __name__ == "__main__": app = MainApp() app.run()在這段代碼中,我想添加WordEntry到來自py的GridLayoutin GetInput(原因是我需要根據(jù)用戶的輸入添加多個)。
1 回答

GCT1015
TA貢獻1827條經(jīng)驗 獲得超4個贊
您可以使用Factory來創(chuàng)建已在 中定義的類的實例kv。所以你的GetCount班級可以是:
from kivy.factory import Factory
class GetCount(Screen):
count_input = ObjectProperty(None)
def next(self):
# Setup next screen
for _ in range(int(self.count_input.text)):
new_word_entry = Factory.WordEntry()
self.manager.ids.get_input.ids.grid.add_widget(new_word_entry)
# Switch to next screen
self.manager.current = "get_input"
添加回答
舉報
0/150
提交
取消