簡體   English   中英

如何在沒有kv語言的Kivy中添加背景圖片

[英]How to add background image in Kivy without kv language

我正在為桌面創建一個 Kivy 應用程序。 我已經創建了大部分應用程序,但我想向應用程序添加背景圖像。 我沒有使用 KV 語言,而是僅使用 Python 代碼創建了所有小部件。 誰能幫我使用 Python 在 kivy 應用程序中添加背景圖像。

您可以使用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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM