Kivy“NoneType”对象没有属性“ids”

2023-12-02

我在 Kivy 应用程序中收到以下错误,但我不确定原因以及如何修复它:

File "main.py", line 16, in __init__
self.seq_text_box = self.parent.ids.seq_text_box
AttributeError: 'NoneType' object has no attribute 'ids'

基本上,我想做的就是访问方法中的文本框MenuBar班级。我对此很陌生,所以很可能我误解了一些东西。

.py file

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput


class SequenceTextBox(TextInput):

    pass
    #...


class MenuBar(BoxLayout):

    def __init__(self, **kwargs):
        super(MenuBar, self).__init__(**kwargs)
        self.seq_text_box = self.parent.ids.seq_text_box

    def go(self):

        print(self.seq_text_box.text)


class MinuRoot(BoxLayout):
    pass


class MinuApp(App):
    pass


if __name__ == '__main__':
    MinuApp().run()

.kv file

MinuRoot:

<MinuRoot>:
    orientation: "vertical"
    MenuBar
    SequenceTextBox
        id: seq_text_box

<MenuBar>:
    height: "40dp"
    size_hint_y: None
    Button:
        text: "Go!"
        on_press: root.go()

<SequenceTextBox>:
    focus: True

我感谢您的帮助 :)


您可以存储seq_text_box as an ObjectProperty of MenuBar并将其设置在kv file:

class MenuBar(BoxLayout):
    seq_text_box = ObjectProperty()
    def go(self):
        print(self.seq_text_box.text)

并在kv file:

<MinuRoot>:
    orientation: "vertical"
    MenuBar:
        seq_text_box: seq_text_box
    SequenceTextBox:
        id: seq_text_box

您收到错误的原因是因为在构造函数中ids尚未从指定的规则中填充kv file.

如果您确实想使用普通属性,您可以安排Clock event:

class MenuBar(BoxLayout):
    def __init__(self, **kwargs):
        super(MenuBar, self).__init__(**kwargs)
        Clock.schedule_once(self.init_seq_text_box, 0)

    def init_seq_text_box(self, *args):
        self.seq_text_box = self.parent.ids.seq_text_box

这将安排一个电话init_eq_text_box对于下一帧,当ids将被填充。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Kivy“NoneType”对象没有属性“ids” 的相关文章

随机推荐