我正在开发一个应用程序,我需要在特定的时间独立显示图像。我已经使用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"))