如何在加载内容之前在 Kivy (Python) 的背景上设置图像?

How to set an image on the background in Kivy (Python) before the content is loaded?

我正在 KIVY 编写天气应用程序,其中启动天气页面时是 运行ning 并且 label 标签设置为温度值。同样在启动时,在分割开始之前,我将图像设置在整个屏幕的背景上。但是当我 运行 应用程序时,没有图像,只有在解析工作后才会加载它。如何在解析开始前安装镜像?

from kivy.app import App
from kivy.uix.relativelayout import RelativeLayout
from kivy.graphics import Rectangle
from kivy.core.window import Window
from kivy.uix.label import Label
from kivy.lang import Builder
import requests
from bs4 import BeautifulSoup
from time import sleep

Builder.load_file('my.kv')

class MainWidget(RelativeLayout):
    intWeather = 0
    
    def __init__(self, ** kwargs):
        super(MainWidget, 
self).__init__( ** kwargs) 
        with self.canvas.before:
    
Rectangle(source='winter.jpg', pos=self.pos, size=Window.size) 
    
        strWeather = self.set_weather()
        self.ids['weather'].text = strWeather+" °C"
        self.intWeather = int(strWeather)  
    
    def set_weather(self):
        url = 'https://pogoda33.ru/%D0%BF%D0%BE%D0%B3%D0%BE%D0%B4%D0%B0-%D1%83%D1%81%D1%82%D1%8C-%D1%82%D1%8B%D0%BC/14-%D0%B4%D0%BD%D0%B5%D0%B9'
        response = requests.get(url)
        soup = BeautifulSoup(response.text, 'html5lib')
        weather = soup.find_all('div', class_='forecast-weather-temperature')
        return weather[0].text[0:3]

class myApp(App):
    def build(self):

        # return a MainWidget() as a root widget
        return MainWidget()

if __name__ == '__main__':
    # Here the class MyApp is initialized
    # and its run() method called.
    myApp().run()

my.kv 文件

<MainWidget>:
    Label:  
        id: weather      
        font_size:150
        pos_hint:{'center_x':.5, 'center_y':.8}

您的背景图片没有如您所愿地立即显示,因为 MainWidget__init__() 方法正在使用主线程访问网络并检索天气。 kivy App 也使用主线程来更新 GUI,所以在你释放主线程之前它无法进行更新。作为一般规则,你不应该在 kivy 应用程序的主线程上做任何长时间的 运行 处理。因此,要解决此问题,请在另一个线程中进行 Web 访问:

class MainWidget(RelativeLayout):
    intWeather = 0

    def __init__(self, **kwargs):
        super(MainWidget, self).__init__(**kwargs)
        with self.canvas.before:
            Rectangle(source='winter.jpg', pos=self.pos, size=Window.size)
        # run web access in another thread
        Thread(target=self.set_weather, daemon=True).start()

    @mainthread
    def show_weather(self, temp):
        # this gets run on the main thread
        self.ids['weather'].text = temp + " °C"
        self.intWeather = int(temp)

    def set_weather(self):
        url = 'https://pogoda33.ru/%D0%BF%D0%BE%D0%B3%D0%BE%D0%B4%D0%B0-%D1%83%D1%81%D1%82%D1%8C-%D1%82%D1%8B%D0%BC/14-%D0%B4%D0%BD%D0%B5%D0%B9'
        response = requests.get(url)
        soup = BeautifulSoup(response.text, 'html5lib')
        weather = soup.find_all('div', class_='forecast-weather-temperature')
        temp = weather[0].text[0:3]
        self.show_weather(temp)