在 Kivy 中引用动态创建的小部件的 ID

sim*_*ail 1 python properties popup kivy

我无法通过绑定到按钮的方法中的root.ids.created_in_kv.created_in_py访问动态创建的子。当我检查root.ids.created_in_kv.ids字典时它是空的,但是root.ids.created_in_kv.children 中有孩子

我想要实现的是创建一个充当多选器的弹出窗口。它将接受可能的选择并动态创建标签-复选框对并将其添加到弹出内容中,并且在“应用”按钮上它将仅返回选择的列表(str())。

我不能在 kv 中构建带有多个小部件的弹出窗口,但以下工作(建议使其“更好”而不是受欢迎):

电压代码:

<SelectorPopup>:
    title: 'empty'
    BoxLayout:
        id: inside
        orientation: 'vertical'
        BoxLayout:
            id: options
        BoxLayout:
            id: buttons
            orientation: 'vertical'
            Button:
                text: 'Apply'
                on_release: root.return_selected()
            Button:
                text: 'Cancel'
                on_release: root.dismiss()

<LabeledCheckbox@BoxLayout>:
    id: entity
    CheckBox:
        id: choice
    Label:
        text: root.id
Run Code Online (Sandbox Code Playgroud)

我正在创建标签-复选框对(打包在 GridLayout 中)并将其放入选项 BoxLayout的 python 代码:

class SelectorPopup(Popup):
    def return_selected(self):
        selected=[]
        a = self.ids.inside.options.choices.ids # dict is empty
        for item in a.keys():
             selected.append(item) if a[item].ids.choice.value #add if checkbox checked
        return selected

class MultiselectForm(BoxLayout):
    data = ListProperty([])
    def __init__(self, **kwargs):
        super(MultiselectForm, self).__init__(**kwargs)
        self.prompt = SelectorPopup()

    def apply_data(self):
        # write data to self.data
        pass

    def create_popup(self):
        try:
            # some code to check if choices are already created
            check = self.prompt.ids.inside.options.choices.id
        except AttributeError:
            possible = ['choice1','choice2','choice3'] #query db for possible instances
            choices = GridLayout(id='choices',cols=2)
            for entity in possible:
                choice = Factory.LabeledCheckbox(id=entity)
                choices.add_widget(choice)
            self.prompt.ids.options.add_widget(choices)
        self.prompt.open()
Run Code Online (Sandbox Code Playgroud)

问题:

1) 如何使return_selected方法工作?

2)有没有办法更好地构建弹出窗口?我无法将小部件树添加到内容ObjectProperty 中,例如:

<MyPopup>:
    content:
        BoxLayout:
            Label:
                text: 'aaa'
            Label:
                text: 'bbb'
Run Code Online (Sandbox Code Playgroud)

bj0*_*bj0 5

看起来您对 ids 的工作方式有点困惑。他们在文档中有一些讨论:https : //kivy.org/docs/api-kivy.lang.html

基本上,它们只是特殊的标记.kv,可以让您引用定义的小部件。它们被收集并放置在定义它们的规则的根小部件上ids字典中。这意味着它们不像您引用它们那样嵌套,它们都在根小部件(或)上SelectorPopupLabeledCheckbox

所以而不是(从内部SelectorPopup):

self.ids.inside.options.choices
Run Code Online (Sandbox Code Playgroud)

你将会拥有:

self.ids.choices
Run Code Online (Sandbox Code Playgroud)

这也意味着动态添加的小部件不会出现在ids字典中,但它们实际上并不需要。由于您是在代码中创建它们,因此您可以自己保存对它们的引用(这很难用.kv)。

尽管如此,使用ListView显示您的项目列表可能要容易得多