Adam Kamil
Adam Kamil

Reputation: 151

kivy how to use online images in python

I'm trying to make a button which uses an image from URL.

icon= str('https://cdn2.iconfinder.com/data/icons/flat-ui-icons-24-px/24/eye-24-256.png')

self.add_widget(ImageButton(source=(icon), size=(100,100), size_hint=(0.1, 0.1), on_press=callback, pos_hint={"x":0.90, "top":1.0}))

class ImageButton(ButtonBehavior, Image):
    pass

It shows as an white image for some reason. Could anyone help me please?

Upvotes: 4

Views: 3868

Answers (1)

FJSevilla
FJSevilla

Reputation: 4543

As eyllanesc comments, you must use AsyncImage subclass to load the image asynchronously from the server. Otherwise, the image will not be available when you instantiate the widget.

On the other hand, the code you show in your comment;

icon = AsyncImage(source='https://.../icon.png')
self.add_widget(ImageButton(source=(str(icon)))

is also incorrect, You are trying to pass to source (StringPropery) an instance of AsyncImage. The simple solution to that is to inherit from AsyncImage and not from Image:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import AsyncImage
from kivy.uix.behaviors import ButtonBehavior

from kivy.core.window import Window
Window.clearcolor = (1, 1, 1, 1)


class ImageButton(ButtonBehavior, AsyncImage):
    pass


class MainWindow(BoxLayout):
    def __init__(self, **kwargs):
        super(MainWindow, self).__init__(**kwargs)
        icon = 'https://cdn2.iconfinder.com/data/icons/flat-ui-icons-24-px/24/eye-24-256.png'
        self.add_widget(ImageButton(source=icon))


class Test(App):
    def build(self):
        return MainWindow()


if __name__ == "__main__":
    Test().run()

enter image description here

Upvotes: 5

Related Questions