Kivy 为一个特定 class 的所有对象设置动画
Kivy animate all objects of one specific class
kivy 中有什么方法可以为某些 class 的所有对象设置动画吗?我有这样的 kv 代码:
<SomeLabel@Label>:
size_hint_x = .5
MainBoxLayout:
some_labels: [some_label1, some_label2, some_label3]
BoxLayout:
SomeLabel:
id: some_label1
SomeLabel:
id: some_label2
SomeLabel:
id: some_label3
和Python代码:
class MainBoxLayout(BoxLayout):
def animate_margins(self):
for some_label in self.some_labels:
Animation(size_hint_x=.1, d=.3, t='out_quint').start(some_label)
它看起来还不错,但在实际程序中我有 10 个这样的标签,将来可能会更多,所以我想知道是否有任何方法可以不分配此 ID 并只为某些 class?
您可以在您制作的自定义小部件上创建一个静态列表,其中包含它的所有实例。
一种方法是将它们附加到 __init__
方法中。
在这个例子中,我制作了一个动画 ToggleButton
供您测试:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.animation import Animation
from kivy.uix.boxlayout import BoxLayout
class SomeLabel(Label):
instances = []
def __init__(self, **kwargs):
super(SomeLabel,self).__init__(**kwargs)
SomeLabel.instances.append(self.proxy_ref)
class MainBoxLayout(BoxLayout):
def animate_margins(self,state):
x, d = (.1, .3) if state == 'down' else (1, 1)
for some_label in SomeLabel.instances:
Animation(size_hint_x=x, d=d, t='out_quint').start(some_label)
root = Builder.load_string('''
MainBoxLayout:
BoxLayout:
ToggleButton:
text: 'Animate'
on_release: root.animate_margins(self.state)
SomeLabel:
text: 'Label 1'
SomeLabel:
text: 'Label 2'
SomeLabel:
text: 'Label 3'
''')
class MyApp(App):
def build(self):
return root
MyApp().run()
kivy 中有什么方法可以为某些 class 的所有对象设置动画吗?我有这样的 kv 代码:
<SomeLabel@Label>:
size_hint_x = .5
MainBoxLayout:
some_labels: [some_label1, some_label2, some_label3]
BoxLayout:
SomeLabel:
id: some_label1
SomeLabel:
id: some_label2
SomeLabel:
id: some_label3
和Python代码:
class MainBoxLayout(BoxLayout):
def animate_margins(self):
for some_label in self.some_labels:
Animation(size_hint_x=.1, d=.3, t='out_quint').start(some_label)
它看起来还不错,但在实际程序中我有 10 个这样的标签,将来可能会更多,所以我想知道是否有任何方法可以不分配此 ID 并只为某些 class?
您可以在您制作的自定义小部件上创建一个静态列表,其中包含它的所有实例。
一种方法是将它们附加到 __init__
方法中。
在这个例子中,我制作了一个动画 ToggleButton
供您测试:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.animation import Animation
from kivy.uix.boxlayout import BoxLayout
class SomeLabel(Label):
instances = []
def __init__(self, **kwargs):
super(SomeLabel,self).__init__(**kwargs)
SomeLabel.instances.append(self.proxy_ref)
class MainBoxLayout(BoxLayout):
def animate_margins(self,state):
x, d = (.1, .3) if state == 'down' else (1, 1)
for some_label in SomeLabel.instances:
Animation(size_hint_x=x, d=d, t='out_quint').start(some_label)
root = Builder.load_string('''
MainBoxLayout:
BoxLayout:
ToggleButton:
text: 'Animate'
on_release: root.animate_margins(self.state)
SomeLabel:
text: 'Label 1'
SomeLabel:
text: 'Label 2'
SomeLabel:
text: 'Label 3'
''')
class MyApp(App):
def build(self):
return root
MyApp().run()