0

[已修改]我按下按钮时出现问题:我总是收到以下错误。谁能建议我如何解决这个问题?

main.py 文件:

class MainApp(MDApp):



    def build(self):
        self.dati = Builder.load_file("conf.kv")
        return Builder.load_file("conf.kv")

    def show_data(self):
        print(self.boxlay.btn_nav.scr1.classe.text)

MainApp().run()

conf.kv 文件:

BoxLayout:
    orientation:'vertical'
    id: boxlay
    btn_nav:btn_nav

    MDToolbar:
        title: 'Bottom navigation'

    MDBottomNavigation:
        id: btn_nav
        scr1:scr1

        MDBottomNavigationItem:
            id: scr1
            classe:classe
            name: 'screen 1'
            text: 'Python'
            icon: 'language-python'

            MDTextField:
                id: classe
                hint_text: "Enter Class"
                pos_hint:{'center_x': 0.5, 'center_y': 0.5}
                size_hint_x:None
                width:300
            MDRectangleFlatButton:
                text: 'Python'
                pos_hint: {'center_x': 0.5, 'center_y': 0.4}
                on_release: app.show_data()

运行此代码,我收到的错误是:

  on_release: app.show_data()
   File "main.py", line 27, in show_data
     print( AttributeError: 'NoneType' object has no attribute 'btn_nav')
 AttributeError: 'BoxLayout' object has no attribute 'classe'

感谢您的帮助

4

1 回答 1

0

由于您已经ids定义,您可以在您的 python 代码中使用它们来访问从您的kv. 所以show_data()方法可以是:

def show_data(self):
    print(self.root.ids.classe.text)

另外,我注意到您正在致电:

Builder.load_file("conf.kv")

build()在你的方法中两次。虽然这不是错误,但它可能不是您想要的。该行:

self.dati = Builder.load_file("conf.kv")

创建由以下行创建的 GUI 的完整副本:

return Builder.load_file("conf.kv")

但是,所引用self.dati的小部件树不是您 GUI 中的小部件树,因此self.dati可能没有任何价值。我怀疑你的build()方法应该是:

def build(self):
    self.dati = Builder.load_file("conf.kv")
    return self.dati
于 2020-08-26T00:56:37.850 回答