[我试图用基维制作带有时钟的动画,当我借助按钮执行功能时,效果很好,但是当我将功能安排在时钟中时,它会抛出错误。
我的python代码是
from kivy.app import App
from kivy.lang import Builder
from kivy.animation import Animation
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock
from kivy.properties import ObjectProperty
login=Builder.load_file('login.kv')
class Login(BoxLayout):
image=ObjectProperty(None)
def press(self):
anim=Animation(size_hint=(.3,.3))
anim &=Animation(pos_hint={'center_x':.5,'center_y':.8})
anim.start(self.image)
Clock.schedule_once(press)
class Main(App):
def build(self):
return Login()
if __name__=="__main__":
Main().run()
我的基维文件是:
<Login>:
image:img
Image:
id:img
source:'22.png'
pos_hint:{'center_x':.5,'center_y':.5}
当我执行程序时,它引发以下错误:
** anim.start(self.image)
AttributeError:“浮动”对象没有属性“图像” **
问题是您的代码Clock.schedule_once(press)
在Login
类中的任何方法之外,因此,在分配该类后,即会在分配image
属性之前执行该代码。因此,解决方案是确保在press()
类就绪之前不调用Login
。您可以通过将Clock.schedule_once()
调用移到build()
的App
方法中来执行此操作。
class Login(BoxLayout):
image=ObjectProperty(None)
def press(self, dt):
anim=Animation(size_hint=(.3,.3))
anim &=Animation(pos_hint={'center_x':.5,'center_y':.8})
anim.start(self.image)
class Main(App):
def build(self):
login = Login()
Clock.schedule_once(login.press)
return login