Reputation: 791
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"
Upvotes: 18
Views: 48004
Reputation: 45
To solve the same problem i use kivyMD so firstly:
I create my custom view which inherit from MDScreen for more flexibility.
The class constructor call the parent constructor to build the screen, then I create an attribute backgroundImage that handle a FitImage object, with the path of your image give at the source attribute. Finally I add the image to screen children and it work
class MainView(MDScreen):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.backgroundImage = FitImage(source="src/background.png")
self.add_widget(self.backgroundImage)
you can refer to these links for more detail over kivyMD:
MDScreen doc
ScreenManager doc
FitImage doc
Upvotes: 0
Reputation: 95
Now there is a simple way to do it, here it just adds the FitImage
MDScreen:
md_bg_color: 239/255, 239/255, 239/255, 1
name:"entrance"
FitImage:
source:"images/yourimagepath.jpg"
MDBoxLayout:
Upvotes: 0
Reputation: 29450
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.
Upvotes: 21