动画子类

时间:2019-05-11 07:56:41

标签: python kivy

在Animation类中,如何默认设置d = 0.4,t ='in_out_quad'?我可以为此使用子类吗?

from kivy.app import App
from kivy.lang import Builder
from kivy.animation import Animation

KV = """
Label
    text: '123'
    on_touch_down: app.test()
"""
class MyApp(App):
    def build(self):
        self.root = Builder.load_string(KV)

    def test(self):
        a = Animation(x = 500, d = .2, t = 'in_out_quad')
        a.start(self.root)

MyApp().run()

尝试过类似的事情(没有成功):

from kivy.app import App
from kivy.lang import Builder
from kivy.animation import Animation

KV = """

Label
    text: '123'
    on_touch_down: app.test()

<MyAnim>:
    d: .2
    t: 'in_out_quad'
"""

class MyAnim(Animation):
    pass

class MyApp(App):
    def build(self):
        self.root = Builder.load_string(KV)

    def test(self):
        a = MyAnim(x = 500)
        a.start(self.root)

MyApp().run()

如果我的项目中的参数d和t值相同,我只是不想多次写它们

1 个答案:

答案 0 :(得分:1)

我还没有测试过,但是我认为您可以将这些默认值放在类定义中:

class MyAnim(Animation):
    def __init__(self, **kw):
        super(MyAnim, self).__init__(d = .2, t = 'in_out_quad', **kw)

当然,如果您使用MyAnim并指定另一个t=d=,则会出现错误。

仅通过添加默认值即可避免该错误:

class MyAnim(Animation):
    def __init__(self, **kw):
        if 'd' not in kw:
            kw['d'] = 0.2
        if 't' not in kw:
            kw['t'] = 'in_out_quad'
        super(MyAnim, self).__init__(**kw)