如何在没有kv语言的情况下在Kivy中添加背景图像

问题描述 投票:0回答:1

我正在为桌面创建Kivy应用。我已经创建了大多数应用程序,但是我想向应用程序添加背景图像。我没有使用KV语言,而是仅使用Python代码创建了所有小部件。谁能帮助我使用Python在kivy应用中添加背景图片。

python python-3.x kivy kivy-language
1个回答
0
投票

您可以使用with canvas:绘制背景图像。这是一个简单的示例:

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()
© www.soinside.com 2019 - 2024. All rights reserved.