首页 > 解决方案 > Kivy:未显示 MDExpansion 面板

问题描述

我需要创建一个屏幕作为结果表测试的历史记录,该屏幕位于另一个屏幕中。我想使用 MDExpansionPanel,但是当我编写代码时没有显示任何内容。屏幕是空的,我不知道为什么,有人可以帮助我吗?

在 main.py

class GoalsScreen(Screen):
    pass
class Content(BoxLayout):
    pass

class HistoryScreen(Screen):

    def on_start(self):
        names = ["test1", "test2", "test3"]

        for name in names:
            panel= MDExpansionPanel(icon="1.png",title= name,
                    content=Content())

            self.root.ids.panel_container.add_widget(panel)

class MainApp(MDApp):

    def build(self):
        self.theme_cls.primary_palette = "Red"
        self.theme_cls.primary_hue = "500"
        self.theme_cls.theme_style = "Light"


        screen = Builder.load_string(screen_helper)
        return screen

MainApp().run()

在.kv


screen_helper = """
ScreenManager:
    GoalsScreen:
    HistoryScreen:

<GoalsScreen>:
    name: "goals"
    Button:
        text: "next page"
        on_press: root.manager.current= "history"
    
<Content>
    size_hint: 1,None
    height: self.minimum_height
    Button:
        size_hint: None, None
    MDIconButton:
        icon: "close"
    
<HistoryScreen>:
    name: "history"
    
    BoxLayout:
        ScrollView:
            GridLayout:
                cols: 1
                size_hint_y: None
                height: self.minimum_height
                id: panel_container

标签: pythonkivykivy-languagekivymd

解决方案


您的代码有几个问题:

  • on_start()方法永远不会被调用(它不会自动调用 a Screen)。
  • title= name不是MDExpansionPanel.
  • 缺少panel_cls所需的参数。MDExpansionPanel
  • HistoryScreen没有root属性,因此此代码将失败:self.root.ids.panel_container.add_widget(panel)

尝试这样的事情:

class HistoryScreen(Screen):
    def on_enter(self):
        self.ids.panel_container.clear_widgets()  # to avoid re-adding panel each time
        names = ["test1", "test2", "test3"]

        for name in names:
            panel= MDExpansionPanel(icon="1.png",panel_cls=MDExpansionPanelOneLine(),
                    content=Content())

            self.ids.panel_container.add_widget(panel)

推荐阅读