Kivy:无法引用.kv文件属性

时间:2018-10-21 02:11:49

标签: python python-3.x kivy kivy-language

我正在使用Python 3.7和Kivy 1.10.1。我似乎无法弄清楚。我试图在Kivy中添加Label(最终是按钮)的动画。但我不断得到:

AttributeError: 'IntroScreen' object has no attribute 'lbl'

class IntroScreen(Screen):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.animate()

    def animate(self):
        anim = Animation(opacity=0, duration=3)
        anim.start(self.lbl)

class MainScreen(GridLayout, Screen):
    pass

class AnotherScreen(GridLayout, Screen):
    pass

class ScreenManagement(ScreenManager):
    pass

presentation = Builder.load_file("blank.kv")

class SimpleKivy(App):
    def build(self):
        self.title = "woods"
        return presentation

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

.kv文件的相关部分如下所示:

# File name: text_game.py
#: import FadeTransition kivy.uix.screenmanager.FadeTransition

ScreenManagement:
    transition: FadeTransition()
    IntroScreen:
    MainScreen:
    AnotherScreen:

<CustButton@Button>:
    font_size: 50
    font_name: "silly"
    color: 0,1,0,1

<IntroScreen>:
    lbl: lbl

    canvas.before:
        Rectangle:
            size: 20, 20
            source: "cabin.png"

    Label:
        id: lbl
        text: "Howdy"

任何帮助将不胜感激。我不明白为什么在.kv文件中找不到lbl属性。预先谢谢你!

1 个答案:

答案 0 :(得分:0)

编译.kv时,要做的是使用.py中声明的基类,然后再添加.kv中指示的属性,以便此时将调用animate()方法,但当时尚未定义尝试使用lbl的位置,因此您会抛出该错误。

因此,在这些情况下,您必须在.kv添加其他属性之后立即调用animate(),为此,我们使用Clock.schedule_once(),如下所示:

from kivy.clock import Clock


class IntroScreen(Screen):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        Clock.schedule_once(lambda *args: self.animate())

    def animate(self):
        anim = Animation(opacity=0, duration=3)
        anim.start(self.lbl)