当我尝试向MDList添加许多小部件时,该应用程序冻结。添加完每个小部件后,我可以更新gui吗?是否可以添加小部件而不会冻结?
from kivy.lang import Builder
from kivy.properties import ObjectProperty
from kivymd.app import MDApp
from kivymd.uix import Screen
from kivymd.uix.button import MDRaisedButton
from kivymd.uix.list import OneLineIconListItem
kv = '''
ScreenManager:
id: screen_mng
Screen:
name: 'scr 1'
Button_:
screen_mng: screen_mng
text: 'scr 2'
on_release:
screen_mng.current = 'scr 2'
Screen_:
list: container_
name: 'scr 2'
on_pre_enter: self.load_items()
ScrollView:
MDList:
id: container_'''
class Button_(MDRaisedButton):
screenmanager = ObjectProperty()
class Screen_(Screen):
list = ObjectProperty()
def load_items(self):
for i in range(100):
item = OneLineIconListItem(text=str(i))
self.list.add_widget(item)
class Test(MDApp):
def build(self):
return Builder.load_string(kv)
app = Test()
app.run()
如果我使用多线程,则没有任何变化,该应用程序仍然冻结
def load_items(self):
Thread(target=self._load_items).start()
def _load_items(self):
for i in range(100):
item = OneLineIconListItem(text=str(i))
self.list.add_widget(item)
请帮助
答案 0 :(得分:0)
感谢所有对我的问题发表评论的人,我做了我需要做的一切。
from kivy.lang import Builder
from kivy.properties import ObjectProperty, StringProperty
from kivymd.app import MDApp
from kivymd.uix import Screen
from kivymd.uix.button import MDRaisedButton
from kivymd.uix.list import OneLineIconListItem
from kivy.uix.recycleview import RecycleView
kv = '''
<ListItem>:
IconLeftWidget:
icon: root.icon
<RV>:
viewclass: 'ListItem'
RecycleBoxLayout:
default_size: None, dp(56)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
<Screen_>:
BoxLayout:
Button_:
text: 'update'
on_release: rv.update()
RV:
id: rv
ScreenManager:
id: screen_mng
Screen:
name: 'scr 1'
Button_:
screen_mng: screen_mng
text: 'scr 2'
on_release:
screen_mng.current = 'scr 2'
Screen_:
name: 'scr 2'
'''
class Button_(MDRaisedButton):
screenmanager = ObjectProperty()
class RV(RecycleView):
def __init__(self, **kwargs):
super(RV, self).__init__(**kwargs)
self.update()
def update(self):
self.data = [{'type': i, 'arg': i**2, 'text': str(i + 1)} for i in range(100)]
class ListItem(OneLineIconListItem):
icon = StringProperty()
def __init__(self, type=None, arg=None, **kwargs):
super().__init__(**kwargs)
self.arg = arg
self.type = type
self.icon = self.__return_icon()
def __return_icon(self):
self.type = 'android'
return 'android'
class Screen_(Screen):
list = ObjectProperty()
def load_items(self):
self.list.update()
class Test(MDApp):
def build(self):
return Builder.load_string(kv)
app = Test()
app.run()