如何在Kivy中设置屏幕背景图像

时间:2015-07-02 08:18:19

标签: kivy

我知道如何制作彩色背景,但我似乎找不到任何有用的设置图像作为背景,并且非常感谢我的代码的任何帮助。

这是我的.py文件:

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

和.kv文件:

#: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"

1 个答案:

答案 0 :(得分:11)

canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
        Image:
            source: "lights.png"

图片是一个小部件,你不能把它放在画布上。

你可以做的只是设置矩形的来源:

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

...或者将您的图像置于其他小部件后面,将它们放在容器布局中。