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

时间:2020-06-30 09:58:35

标签: python kivy kivy-language

此代码中出现错误,我试图更改按钮的颜色。

代码:

Builder.load_string('''
<FileBrowserApp>:
    Button:
        id: 'b1'
        text: 'Select Files'
        pos_hint: {'x':0, 'y': 0}
        size_hint: (1, 0.1)
        on_press: self.do_select
        on_press: self.background_color=[0,0,255,1]
        on_release: self.background_color=[192,192,19,1]   
''')


class FileBrowserApp(App):
    def build(self):
        try:
            if(self.out):
            self.root.remove_widget(self.out)
        except:
            pass

        self.root = FloatLayout()
        self.bn = BoxLayout(orientation="horizontal")

        button1 = self.ids['b1']
    
        self.bn.add_widget(button1)

        self.out = BoxLayout(orientation="vertical")

        self.root.add_widget(self.out)
        self.root.add_widget(self.bn)
        
        return self.root

错误:

Traceback (most recent call last):
File "kk.py", line 120, in <module>
 app.run()
File "/usr/lib/python3/dist-packages/kivy/app.py", line 800, in run
 root = self.build()
File "kk.py", line 47, in build
 button1 = self.ids['b1']
AttributeError: 'FileBrowserApp' object has no attribute 'ids'

Builder.load_string()允许多个类创建kv语言

如何解决此错误?

1 个答案:

答案 0 :(得分:0)

您似乎无法尝试在Button中添加FileBrowserAppkv。您的构造适合将Button添加到容器(例如Layout)中,但是App不是容器。如果您想在Button中定义kv,可以通过定义一个扩展Button的新类来做到这一点:

class SelectFileButton(Button):
    pass

然后在SelectFileButton中为kv创建一个规则:

Builder.load_string('''
<SelectFileButton>:
    text: 'Select Files'
    pos_hint: {'x':0, 'y': 0}
    size_hint: (1, 0.1)
    on_press: app.do_select()
    on_press: self.background_color=[0,0,255,1]
    on_release: self.background_color=[192,192,19,1]   
''')

此规则定义了如何配置SelectFileButton,然后可以在build()方法中使用它:

class FileBrowserApp(App):
    def build(self):
        try:
            if (self.out):
                self.root.remove_widget(self.out)
        except:
            pass

        self.root = FloatLayout()
        self.bn = BoxLayout(orientation="horizontal")

        # create a Button based on the kv rule
        button1 = SelectFileButton()
        self.bn.add_widget(button1)

        self.out = BoxLayout(orientation="vertical")

        self.root.add_widget(self.out)
        self.root.add_widget(self.bn)

        return self.root

    def do_select(self):
        print('do select')

这是一种实现方法,但是更好的方法可能是在kv中创建一条规则,该规则描述应如何构建FileBrowserApp的整个根。然后build()方法将简单地返回该根。或者,如果您将kv放在名为filebrowser.kv的文件中,则甚至不需要build()方法。参见documentation