Reputation: 171
How do i animate an object with a reusable method when it's being added/removed from the layout
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()
In the above code the Add method adds the Factory object Image1 into the layout
Upvotes: 0
Views: 28
Reputation: 39152
You can use Animation
(See the documentation). Adding some methods to your Image_1
class makes it easier. Here is a modified version of your code that uses 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()
Upvotes: 1