I'm using Python 3.7 and Kivy 1.10.1. I cannot seem to figure this out. I am trying to add an animation of a Label (eventually a button) in Kivy. But I keep getting:
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()
And the relevant part of my .kv file looks like this:
# 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"
Any help would be much appreciated. I don't see why it's not finding the lbl attribute in the .kv file. Thank you in advance!
When compiling the .kv, what is done is to use the base classes that are declared in the .py before adding the properties indicated in the .kv, so that at that moment the animate()
method will be called, where try to use lbl and clearly is not defined at that time, so you throw that error.
So in these cases you must call animate()
an instant after the .kv adds the other properties and for this we use Clock.schedule_once()
as I show below:
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)