【问题标题】:Kivy: Cannot refer to .kv file attributeKivy:无法引用 .kv 文件属性
【发布时间】:2018-10-21 02:11:48
【问题描述】:

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

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 属性。提前谢谢!

【问题讨论】:

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


    【解决方案1】:

    在编译 .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)
    

    【讨论】:

    • 太棒了,非常感谢!我实际上是打算淡入标签,而不是淡出,但是当我将不透明度设置为 1 时,它不会淡入。有没有快速的解决方案?
    • @rushinstuffin 使用 def animate(self): self.lbl.opacity = 0.0 anim = Animation(opacity=1.0, duration=3) anim.start(self.lbl)
    猜你喜欢
    • 2018-11-04
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 2021-02-16
    • 1970-01-01
    相关资源
    最近更新 更多