Kivy AttributeError:'NoneType'对象没有属性'ids'

时间:2020-05-27 17:00:00

标签: python kivy attributeerror

我在kv文件中创建了一个自定义按钮,如果app.root.ids.my_label ==“ disabled”,我想将Disabled = True设置为true,否则将其设置为False。但是我一直在获取AttributeError:'NoneType'对象没有属性'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()

2 个答案:

答案 0 :(得分:0)

您可以通过将表达式放在每个CustomBtn下来做到这一点,就像这样:

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

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

答案 1 :(得分:0)

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

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()