在Kivy中将BoxLayout切换为垂直并通过id在Python代码中获取小部件

1 投票
1 回答
1394 浏览
提问于 2025-04-18 12:43

我正在创建一个手风琴控件,当我在文本输入框中按下回车键时,它会出现。

以下是我的Python代码:

class LabelNavigatorWidget(BoxLayout):
    def create_accordion_widget(self):
        self.cleanup_root()
        root = Accordion(id='accordion_widget', orientation='vertical')
        for x in range(2):
            item = AccordionItem(title='Title %d' % x)
            item.add_widget(Label(text='Very big content\n' * 10))
            root.add_widget(item)
        self.add_widget(root)
        return root

    def cleanup_root(self):
        # Remove previous widget
        for child in self.children:
            if child.id == 'accordion_widget':
                self.remove_widget(child)

class LabelNavigatorApp(App):
    def build(self):
        return LabelNavigatorWidget()

if __name__ == "__main__":
    LabelNavigatorApp().run()

下面是kv代码:

<LabelNavigatorWidget>:
    BoxLayout:
        orientation: 'vertical'
        TextInput:
            id: label_input
            font_size: 30
            pos: 0, 0
            size_hint_y: None
            height: 50
            multiline: False
            text: ''
            on_text_validate: root.create_accordion_widget(); self.text = ''

这就是它的样子:

不正确的BoxLayout

  1. 默认情况下,BoxLayout是横向的,我该如何将它设置为纵向?
  2. 文本输入框最初的位置在BoxLayout的底部,我该如何让它位于顶部?
  3. 每当我按下回车键时,它会创建一个新的手风琴控件——这就是我在创建新控件之前移除之前控件的原因。不过,有没有更好的方法可以通过ID获取子控件,然后移除它,而不是遍历所有子控件?

1 个回答

3

默认情况下,BoxLayout是横向的,我该如何设置成纵向的呢?

和其他BoxLayout设置一样,只需要把 orientation: 'vertical' 设定一下就可以了。

<LabelNavigatorWidget>:
    orientation: 'vertical'
    BoxLayout:
        orientation: 'vertical'

文本输入框最开始的位置是在BoxLayout的底部,我该如何让它在顶部呢?

可以添加一个空的控件来填充剩余的空间。

BoxLayout:
    orientation: 'vertical'
    TextInput:
        size_hint_y: None
        height: 50
        # ... and the rest
    Widget:

每当我按下回车键时,它会创建一个新的手风琴控件——所以我在创建新控件之前会先删除之前的控件。不过,有没有更好的方法可以直接通过ID获取子控件,然后删除它,而不是一个个遍历所有子控件呢?

你可以把它作为一个属性保存,比如 self.accordion_widget = AccordionWidget(...),然后再用 self.remove_widget(self.accordion_widget) 来删除它。

撰写回答