Skip to content

Instantly share code, notes, and snippets.

@tito
Created March 24, 2023 23:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tito/72a8089f1dce6335e35a7cd81a6a7317 to your computer and use it in GitHub Desktop.
Save tito/72a8089f1dce6335e35a7cd81a6a7317 to your computer and use it in GitHub Desktop.
Kivy Widget for showing/hidding content.
from kivy.uix.relativelayout import RelativeLayout
from kivy.properties import BooleanProperty, NumericProperty
from kivy.animation import Animation
class VisibleContainer(RelativeLayout):
visible = BooleanProperty(True)
animated = BooleanProperty(False)
duration = NumericProperty(0.2)
capture = BooleanProperty(False)
def __init__(self, **kwargs):
self.saved_children = []
self.anim = None
super().__init__(**kwargs)
def add_widget(self, child):
if child not in self.saved_children:
self.saved_children.append(child)
if not self.visible:
return
super().add_widget(child)
def remove_widget(self, child):
if child in self.saved_children:
self.saved_children.remove(child)
if not self.visible:
return
super().remove_widget(child)
def _populate(self):
self._unpopulate()
for child in self.saved_children:
super().add_widget(child)
def _unpopulate(self):
for child in self.saved_children:
super().remove_widget(child)
def on_visible(self, *largs):
if self.visible:
self._populate()
if self.animated:
self.fade_in()
else:
if self.animated:
self.fade_out()
else:
self._unpopulate()
def cancel_anim(self):
if self.anim:
self.anim.cancel_all(self)
def fade_in(self):
self.cancel_anim()
self._populate()
self.opacity = 0
self.anim = Animation(opacity=1, duration=self.duration)
self.anim.start(self)
def fade_out(self):
self.cancel_anim()
self._populate()
self.opacity = 1
self.anim = Animation(opacity=0, duration=self.duration)
self.anim.bind(on_complete=self.on_fade_out_complete)
self.anim.start(self)
def on_fade_out_complete(self, *largs):
for child in self.saved_children:
super().remove_widget(child)
def on_touch_down(self, touch):
ret = super().on_touch_down(touch)
return ret or (self.capture and self.visible)
def on_touch_move(self, touch):
ret = super().on_touch_move(touch)
return ret or (self.capture and self.visible)
def on_touch_up(self, touch):
ret = super().on_touch_up(touch)
return ret or (self.capture and self.visible)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment