【问题标题】:Animation on adding or removal of an object添加或删除对象的动画
【发布时间】:2022-01-24 06:19:30
【问题描述】:

当从布局中添加/删除对象时,如何使用可重用方法为对象设置动画


from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.factory import Factory 

kv='''
<Image_1@BoxLayout>:

    orientation:'vertical'
    #id:img_1   
    Image:
        source:"/storage/emulated/0/Download/download (37).jpeg"
    Button:
        text:"remove"
        on_press: self.parent.remove()             

BoxLayout:
    orientation:'vertical'
                            
    GridLayout:
        cols:1
        id:sc_grid
        
        Button:
            size_hint:None,None 
            text:"add"
            on_press:
                app.Add()      
                              
'''
class MyApp(MDApp):
    
    def build(self):
        return Builder.load_string(kv)
    
    def Add(self):
        
        Image=Factory.Image_1()
        Image.remove = lambda: self.root.ids.sc_grid.remove_widget(Image)
        self.root.ids.sc_grid.add_widget(Image)   
        
MyApp().run()

在上面的代码中,Add 方法将工厂对象 Image1 添加到布局中

【问题讨论】:

    标签: python kivy


    【解决方案1】:

    您可以使用Animation(请参阅documentation)。将一些方法添加到您的 Image_1 类使其更容易。这是使用Animation的代码的修改版本:

    from kivy.animation import Animation
    from kivy.uix.boxlayout import BoxLayout
    from kivymd.app import MDApp
    from kivy.lang import Builder
    
    kv = '''
    <Image_1>:
    
        orientation:'vertical'
        #id:img_1   
        Image:
            source:"/storage/emulated/0/Download/download (37).jpeg"
        Button:
            text:"remove"
            on_press: self.parent.remove()             
    
    BoxLayout:
        orientation:'vertical'
    
        GridLayout:
            cols:1
            id:sc_grid
    
            Button:
                size_hint:None,None 
                text:"add"
                on_press:
                    app.Add()      
    
    '''
    
    class Image_1(BoxLayout):
        def on_parent(self, *args):
            if self.parent:
                self.opacity = 0
                anim = Animation(opacity=1)
                anim.start(self)
    
        def remove(self):
            anim = Animation(opacity=0)
            anim.start(self)
            anim.on_complete = self.do_actual_remove
    
        def do_actual_remove(self, widget):
            self.parent.remove_widget(self)
    
    class MyApp(MDApp):
    
        def build(self):
            return Builder.load_string(kv)
    
        def Add(self):
            Image = Image_1()
            self.root.ids.sc_grid.add_widget(Image)
    
    
    MyApp().run()
    

    【讨论】:

      猜你喜欢
      • 2017-06-13
      • 2022-01-16
      • 2011-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多