简体   繁体   中英

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM