我正在尝试向滚动视图添加很多 boxlayout 小部件,当我刷新屏幕时,我试图将它们全部清除并添加新的一组,但我不明白为什么需要更长的时间每次刷新以添加相同数量的小部件时都会更长?似乎 clear_widget() 清除了屏幕,但它不会删除对类的引用,因此它占用了内存。我是个新手,所以我在做的事情上可能 100% 是错误的,但任何指导都值得赞赏。谢谢!
from kivy.lang import Builder
from kivymd.app import MDApp
from kivy.properties import StringProperty
from kivymd.uix.boxlayout import MDBoxLayout
from datetime import datetime
from kivy.clock import Clock
import sys, os, psutil
kv = """
<hourly_banner>
orientation: "vertical"
MDSeparator:
MDBoxLayout:
size_hint: 0.95, 1
pos_hint: {"center_x": .5}
orientation: "horizontal"
MDLabel:
size_hint_x: 0.475
text: root.weather_code
font_size: self.height * 0.275
halign: "center"
MDBoxLayout:
size_hint_x: 0.2
MDIcon:
icon: root.percip_icon
font_size: self.height*0.375
MDLabel:
text: root.percip_percent
font_size: self.height*0.275
halign: "center"
MDSeparator:
Screen:
MDScrollViewRefreshLayout:
id: refresh_layout_hourly
refresh_callback: app.refresh_callback_hourly
root_layout: root
pos_hint: {"center_x": .5}
MDGridLayout:
id: hourly_grid
cols: 1
adaptive_height: True
padding: "10dp", "0dp"
row_default_height: "50dp"
row_force_default: True
"""
class hourly_banner(MDBoxLayout):
percip_percent = StringProperty()
weather_code = StringProperty()
percip_icon = StringProperty()
class Test(MDApp):
def build(self):
return Builder.load_string(kv)
def on_start(self):
self.setup_screen()
def setup_screen(self):
hourly_grid = self.root.ids['hourly_grid']
print("Before clear Memory = {0}".format(psutil.Process(os.getpid()).memory_info().rss / 1024 ** 2))
print("Ref before clear = {0}".format(sys.getrefcount(hourly_banner)))
self.root.ids['hourly_grid'].clear_widgets()
print("After clear Memory = {0} ".format(psutil.Process(os.getpid()).memory_info().rss / 1024 ** 2))
print("Ref After clear = {0}".format(sys.getrefcount(hourly_banner)))
before = datetime.now()
for i in range(109):
hourly_grid.add_widget(hourly_banner(weather_code="Freezing Heavy Rain", percip_icon="water-percent",
percip_percent="0"))
print("Time to add widgets = {}".format(datetime.now() - before))
self.root.ids.refresh_layout_hourly.refresh_done()
def refresh_callback_hourly(self, *args):
print("\nrefresh callback 2")
def refresh_callback(dt):
self.setup_screen()
Clock.unschedule(refresh_callback)
Clock.schedule_once(refresh_callback, 1)
if __name__ == '__main__':
Test().run()