Kivy - Effects



The Kivy library provides the "kivy.effects" subpackage to control the overscroll effects when using the ScrollView widget in a Kivy app. The Effect classes can perform actions like bouncing back, changing opacity, or prevent scrolling beyond the normal boundaries.

There are three Effect classes −

  • ScrollEffect − Base class used for implementing an effect. It only calculates the scrolling and the overscroll. This class is defined in kivy.effects.scroll module

  • DampedScrollEffect − Uses the overscroll information to allow the user to drag more than expected. Once the user stops the drag, the position is returned to one of the bounds. The definition of this class is in kivy.effects.dampedscroll module.

  • OpacityScrollEffect − Uses the overscroll information to reduce the opacity of the scrollview widget. When the user stops the drag, the opacity is set back to 1. The class definition is available in kivy.effects.opacityscroll module.

These classes use the KineticEffect as the base class for computing velocity out of a movement.

To apply the effect of any of these classes on the scrolling behavior of ScrollView, set one of these classes as the value of effect_cls property of ScrollView widget.

scr = ScrollView(size=Window.size)
scr.eefect_cls=ScrollEffect

Example

The following "kv" language script constructs a ScrollView with a hundred buttons added to a GridLayout. The "effect_cls" property is set to ScrollEffect class.

#:import ScrollEffect kivy.effects.scroll.ScrollEffect
#:import Button kivy.uix.button.Button
<RootWidget>
   effect_cls: ScrollEffect
   GridLayout:
   size_hint_y: None
   height: self.minimum_height
   cols: 1
   on_parent:
      for i in range(100):
self.add_widget(Button(text=str(i), size_hint_y=None))

The above "kv" code uses a class rule by the name RootWidget. The build() method of the App class in the following Python code returns an object of RootWidget class.

from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.effects.dampedscroll import DampedScrollEffect
from kivy.core.window import Window
from kivy.app import App
from kivy.core.window import Window

Window.size = (720,350)

class RootWidget(ScrollView):
   pass
   
class scrollableapp(App):
   def build(self):
      return RootWidget()

scrollableapp().run()

Output

Execute the above Python program from command line. You get the app window with a scrollview, showing a snapshot of buttons. You can scroll up or down with the ScrollEffect activated.

Kivy Effects

You can customize the Effect class by specifying the attributes in the RootWidget class and use it as the "effect_cls" property.

For example, you can set the max and min boundaries to be used for scrolling. The overscroll property is the computed value when the user overscrolls, i.e., goes out of the bounds.

Advertisements