Home > Software design >  Why can't I add an image using kivy in the main.py?
Why can't I add an image using kivy in the main.py?

Time:09-17

Code:

from kivy.uix.widget import Widget
from kivy.uix.image import Image

class MainWidget(Widget):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.add_cloud()

    def add_cloud(self):
        img = Image(source="images/cloudbig.png")
        return img

class TestApp(App):
    pass

TestApp().run()

What should happen is open the app using the Kivy library, add a widget, then an add an image. Though the image isn't showing up in the window, I just get an empty window.

I tried adding the image using a separate .kv file which worked but I need to have adding the image in a function in the .py file to loop the function.

How could I fix the image not showing on the screen?

CodePudding user response:

The reasons to this problem of yours are:

  • you can't add the widget(the Image widget, in your case specifically) just by returning the object from a method/function, but by using the self.add_widget method
  • you didn't create any build method inside your TestApp class, which is essentially required if you don't use the kivy design language

And here's your code example, fixed:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.image import Image


class MainWidget(Widget):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.add_cloud()

    def add_cloud(self):
        img = Image(source="images/cloudbig.png")
        self.add_widget(img)

class TestApp(App):
    def build(self):
        xd = MainWidget()
        return xd

TestApp().run()
  • Related