Naman Jain
Naman Jain

Reputation: 38

How to add background image in Kivy without kv language

I'm creating an Kivy App for Desktop. I've created most of the app but I want to add a background image to the app. I've not use the KV language but created all the widgets using Python code only. Can anybody please help me adding a background image in the kivy app using Python.

Upvotes: 0

Views: 626

Answers (1)

John Anderson
John Anderson

Reputation: 38947

You can use with canvas: to draw a background image. Here is a simple example:

from kivy.app import App
from kivy.clock import Clock
from kivy.graphics.vertex_instructions import Rectangle
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label


class TestApp(App):
    def build(self):
        theRoot = FloatLayout()

        # draw the background
        with theRoot.canvas:
            self.rect = Rectangle(source='background.png')

        # use binding to insure that the background stay matched to theRoot
        theRoot.bind(on_size=self.update)
        theRoot.add_widget(Label(text="Hi", size_hint=(None, None), size=(100, 50), pos=(100,100)))

        # need to call update() to get background sized correctly at start
        Clock.schedule_once(self.update, -1)
        return theRoot

    def update(self, *args):
        # set the size and position of the background image
        self.rect.size = self.root.size
        self.rect.pos = self.root.pos


TestApp().run()

Upvotes: 2

Related Questions