从线程创建时图像不显示 kivy/kivymd

Image not showing when created from a thread kivy/kivymd

我正在开发一个应用程序,我需要图像在特定时间独立显示。我已经使用 python 的库存线程模块设置了一个线程,它正常运行和工作,而不是它显示黑色方块的图像。有人知道怎么解决吗?

这是我重现问题的代码:

import threading
from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout

class TestApp(App):
    def build(self):
        self.fl = FloatLayout()
        self.fl.add_widget(Button(text="show image", on_press=self.start_thread))
        return self.fl

    def insertfunc(self):
        self.fl.add_widget(Image(source="HeartIcon.png"))

    def start_thread(self, instance):
        threading.Thread(target=self.insertfunc).start()

TestApp().run()

任何帮助将不胜感激!

add_widget()必须在主线程上完成。我假设您正在使用 threading,因为除了 add_widget() 之外,您在 Thread 上还有其他事情要做。基于该假设,这里是您的代码的修改版本,可以满足您的要求:

import threading

from kivy.app import App
from kivy.clock import Clock
from kivy.uix.image import Image
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout

class TestApp(App):
    def build(self):
        self.fl = FloatLayout()
        self.fl.add_widget(Button(text="show image", on_press=self.start_thread))
        return self.fl

    def insert_image(self, dt):
        self.fl.add_widget(Image(source="HeartIcon.png"))

    def insertfunc(self):
        # do some calculations here
        Clock.schedule_once(self.insert_image)

    def start_thread(self, instance):
        threading.Thread(target=self.insertfunc).start()

TestApp().run()

如果您没有在新线程中执行任何其他操作,那么您实际上不需要另一个线程。 start_thread() 方法可以做到:

self.fl.add_widget(Image(source="HeartIcon.png"))