Kivy AttributeError: 'NoneType' object has no attribute 'ids'

Kivy AttributeError: 'NoneType' object has no attribute 'ids'

我在 kv 文件中创建了一个自定义按钮,我想设置 disabled = True if app.root.ids.my_label == "disabled" else disabled=False。但是我不断收到 AttributeError: 'NoneType' object has no attribute 'ids.我不可以这样做,我不只是做对了,我将不胜感激任何帮助。谢谢!

test.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.properties import ObjectProperty

Builder.load_string('''
<CustomBtn@Button>
       disabled: True if app.root.ids.word.my_label == "disable" else False

<main>:
my_label:my_label
BoxLayout:
    orientation:"vertical"

    Label:
        id: my_label
        text: "Disabled"
    CustomBtn:
        text: "Btn1"
    CustomBtn:
        text: "Btn2"
    CustomBtn:
        text: "Btn3"
    Button:
        text: "Disable/Enable"
        on_press: root.disablebtn()
        ''')


class main(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        my_label = ObjectProperty()

    def disablebtn(self):
        print(self.my_label)
        if self.my_label.text == "Disabled":
            self.my_label.text = "Enabled"
        else:
            self.my_label.text = "Disabled"


class CallApp(App):
    def build(self):
        return main()


CallApp().run()

您可以将表达式放在每个 CustomBtn 下,如下所示:

    CustomBtn:
        text: "Btn1"
        disabled: True if root.my_label.text == "Disabled" else False

而不是在 <CustomBtn>: 规则中。

您原来的方法行不通,因为在应用您的 <CustomBtn@Button> 规则时未设置 app.root。这是您的代码的修改版本,它可以满足您的需求而不会出现该问题:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.properties import ObjectProperty
from kivy.uix.button import Button


class CustomBtn(Button):
    pass

Builder.load_string('''
<main>:
    my_label:my_label
    BoxLayout:
        orientation:"vertical"

        Label:
            id: my_label
            text: "Disabled"
        CustomBtn:
            text: "Btn1"
        CustomBtn:
            text: "Btn2"
        CustomBtn:
            text: "Btn3"
        Button:
            text: "Disable/Enable"
            on_press: root.disablebtn()
        ''')


class main(BoxLayout):
    my_label = ObjectProperty()

    def disablebtn(self):
        if self.my_label.text == "Disabled":
            self.my_label.text = "Enabled"
            self.disable_customBtns(False)
        else:
            self.my_label.text = "Disabled"
            self.disable_customBtns(True)

    def disable_customBtns(self, is_disabled):
        # Look for CustomBtn instances, and set their `disabled` value
        for child in self.walk():
            if isinstance(child, CustomBtn):
                child.disabled = is_disabled

    def on_my_label(self, *args):
        # this just sets the initial value of disabled to True
        self.disable_customBtns(True)



class CallApp(App):
    def build(self):
        return main()

CallApp().run()