Kivy - Data Loader



A Loader class in Kivy framework is an asynchronous data loader that makes it possible to load an image even if its data is not yet available. This feature is of particular use when you want to load image from an internet URL.

The Loader class is defined in kivy.loader module. Typical use of Loader class is like this −

from kivy.loader import Loader
image = Loader.image('http://mysite.com/test.png')

Use the loading_image property to specify a default image.

Loader.loading_image = Image(default.png')

The Loader class is equipped with the following properties −

  • error_image − Image used for error. For example −

Loader.error_image = 'error.png'
  • image(filename) − Load a image using the Loader. A ProxyImage is returned with a loading image.

  • loading_image − Image used for loading. For example −

Loader.loading_image = 'loading.png'
  • max_upload_per_frame − The number of images to upload per frame. By default, we'll upload only 2 images to the GPU per frame.

  • num_workers − Number of workers to use while loading. This setting impacts the loader only on initialization. Once the loader is started, the setting has no impact.

from kivy.loader import Loader
Loader.num_workers = 4

The default value is "2" for giving a smooth user experience.

  • ProxyImage() − Image returned by the Loader.image() function.

proxyImage = Loader.image("test.jpg")
  • pause() − Pause the loader.

  • resume() − Resume the loader, after a pause().

  • run() − Main loop for the loader.

  • start() − Start the loader thread/process.

  • stop() − Stop the loader thread/process.

The "on_load" event is fired when the image is loaded or changed. Similarly, the "on_error" is fired when the image cannot be loaded. "error: Exception data that occurred".

Example

In the code given below, the Loader object loads an image from an internet URL. The ProxyImage object returned by the Loader binds to a method on its on_load event. The callback method uses its texture as the texture property of the Image object.

from kivy.app import App
from kivy.uix.image import Image
from kivy.loader import Loader
from kivy.core.window import Window

Window.size = (720,400)

class MyApp(App):

   title='Loader'
   
   def _image_loaded(self, proxyImage):
   if proxyImage.image.texture:
      self.image.texture = proxyImage.image.texture
   def build(self):
      proxyImage = Loader.image('https://source.unsplash.com/user/c_v_r/640x480')
      proxyImage.bind(on_load=self._image_loaded)
      self.image = Image()
      return self.image
MyApp().run()

Output

On execution, it will produce the following output −

Kivy Data Loader
Advertisements