首页 > 解决方案 > 如何为另一个按钮 KivyMD 创建的按钮设置动画?

问题描述

我对 KivyMD 很陌生,你们能帮我了解如何为另一个按钮创建的按钮设置动画吗?就像我从 FloatingActionSpeedDial 按钮中单击了一个按钮一样,它会创建另一个按钮,我如何为它的条目设置动画?谢谢!

标签: pythonkivykivy-languagekivymd

解决方案


您的解决方案有两个步骤:

  1. 创建按钮
  2. 动画它

add_widget(Button)现在您通常使用该方法创建一个。这将在屏幕上添加一个按钮,并在内部将其添加到父小部件子级。

然后您要做的是为按钮设置动画,这是使用Animation模块完成的(请参阅https://kivy.org/doc/stable/api-kivy.animation.html

现在我不知道你想如何为你的按钮设置动画,因为可能性几乎是无穷无尽的,但这里有一些代码示例,当你按下屏幕上的按钮时,会添加一个新按钮并向右增长尺寸。

from kivy.app import App
from kivy.animation import Animation
from kivy.lang import Builder
from kivy.uix.button import Button

kv = Builder.load_string(
    """
FloatLayout:
    Button:
        size_hint: 0.3, 0.3
        pos_hint: {'center_x': 0.5, 'center_y': 0.3}
        text: 'Add Button!'
        on_release: app.add_button()
"""
)


class MyMainApp(App):

    def build(self):
        return kv

    def add_button(self):
        """
        Function first creates a button of size [0, 0] and opacity 0 (invisible), then adds it to the screen. Next it 
        animates it so that the size is the same as the last button and the opacity is 1. 
        """
        last_button = self.root.children[-1]
        button = Button(
            size_hint=[0, 0],
            pos=[last_button.x + last_button.width/2, last_button.top + last_button.height/2],
            text='Added',
            opacity=0
        )
        self.root.add_widget(button)
        animation = Animation(size_hint=[0.3, 0.3], pos=[last_button.x, last_button.top], opacity=1)
        animation.start(button)


if __name__ == '__main__':
    MyMainApp().run()

推荐阅读