How to set a screen background image in Kivy

Larisa picture Larisa · Jul 2, 2015 · Viewed 28.3k times · Source

I know how to make a color background but i can't seem to find anything useful for setting the image as a background and would be really grateful for any help with my code.

Here is my .py file:

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout
#from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.core.window import Window
from kivy.core.image import Image
#from kivy.graphics import BorderImage
from kivy.graphics import Color, Rectangle
#from kivy.uix.image import AsyncImage


class StartScreen(Screen):
    pass

class GameScreen(Screen):
    pass

class RootScreen(ScreenManager):
    pass


class MainApp(App):
    def build(self):
        return RootScreen()

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

And .kv file:

#:import FadeTransition kivy.uix.screenmanager.FadeTransition

<RootScreen>:
    transition: FadeTransition() 
    StartScreen:
    GameScreen:

<StartScreen>:
    name: "start"
    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
        Image:
            source: "lights.png"
    FloatLayout:
        Image:     # This part doesn't seem to work
            source: "lights.png"
            allow_stretch: True
            keep_ratio: False
            size_hint: 1, 1
        Button:
            text: "Play!"
            size_hint: 0.4, 0.3
            pos_hint: {'center_x':.5, 'center_y':.5}
            font_size: 70
            on_release: root.manager.current = "game"
<GameScreen>:
    name: "game"
    FloatLayout:
        Button:
            text: "Nazaj!"
            font_size: 70
            on_release: root.manager.current  = "start"

Answer

inclement picture inclement · Jul 2, 2015
canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
        Image:
            source: "lights.png"

Image is a widget, you can't place it on the canvas.

What you *can do is either just set a source for the Rectangle:

canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
            source: 'lights.png'

...or place your Image behind the other widgets by putting them in a container layout.