有兩種方法,並從中選擇取決於如果你想小部件能夠被垃圾收集(從內存免費)或不:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.weakproxy import WeakProxy
from kivy.uix.boxlayout import BoxLayout
from kivy.graphics import Color, Ellipse, Line
from random import randint as r
class Dot(Widget):
def __init__(self, dot_color=None, **kwargs):
super(Dot, self).__init__(**kwargs)
if not dot_color:
raise Exception('No color available!')
self.dot_color = dot_color
# call draw automatically
self.draw()
def draw(self):
with self.canvas:
Color(*self.dot_color)
Ellipse(pos=self.pos, size=self.size)
class TestApp(App):
def build(self):
colors = ((1, 0, 0),
(0, 1, 0),
(0, 0, 1))
do_weak_referencing = False # change to True for weakrefs
if do_weak_referencing:
# get the class for weak referencing
# variant 1
wp = WeakProxy
self.dots = [
WeakProxy(
Dot(dot_color=dc,
pos=(r(100, 500), r(100, 500)))
) for dc in colors]
else:
# variant 2
self.dots = [
Dot(dot_color=dc,
pos=(r(100, 500), r(100, 500))
) for dc in colors]
box = BoxLayout()
for dot in self.dots:
# where will our dot be?
print(dot.pos)
box.add_widget(dot)
# what the list look like?
print(self.dots)
return box
if __name__ == '__main__':
TestApp().run()
注意,如果對象是一個列表爲WeakProxy
,並且沒有添加到任何地方(作爲孩子),它將被收集,如果您稍後嘗試訪問它,則會引發一個錯誤,顯示它不可用(顯然) - 變體1.
但是,如果您選擇直接參考強參考,則不會收集該對象,除非從self.dots
列表中彈出。
我__init__
把self.draw()
直接,這樣你可以看到那裏的點是,但你可以將其刪除,並直接從App.dots
調用它如:
app = App.get_running_app()
app.dots[0].draw()
# tada!
爲了顯示對在平民'add_widget'部件父小部件被使用。另外我會建議使用kv語言進行樣式設計,這很簡單,並且可以在引用更改屬性時解決問題。 – syntonym
小工具是普通的python對象,所以你可以做任何你想要的東西(例如,將它們存儲在一個列表中,在一個字典中,給它們函數......)。 – syntonym