首页 > 解决方案 > 如何在kivy中使用weakref迭代不同的ids级别

问题描述

我有这个ids序列。

self.ids.cuarta_pantalla.ids.container.ids.pre_1.ids.Si

在这种情况下,容器有 70 个不同的 id [从pre_1pre_70 ],每个 pre_(x) 有三个不同的 id [ SiMasMenosNo ],它们对应于一组CheckBoxes

如果我想知道使用其属性的单个复选框的状态,我不得不像这样编写所有语句。

self.ids.cuarta_pantalla.ids.container.ids.pre_1.ids.Si.value.

那么,我怎样才能遍历 id?

我试过使用方括号self.ids.cuarta_pantalla.ids.container.ids['pre_1'],但它返回的东西我不能调用任何方法。

用方括号打印:<weakref at 0x125F7118; to 'BoxLayout' at 0x125F30D0>

用点符号打印:<kivy.uix.boxlayout.BoxLayout object at 0x125F30D0>


这是我创建对象的方式:

for idx in range(70):

  BoxContainer = BoxLayout()

  # Repeat this two more times with MasMenos and No

  check1 = CheckBox(group= f"p_{idx+1}")
  BoxContainer.add_widget(check1)
  BoxContainer.ids['Si'] = weakref.ref(check1)


  #Adding the BoxContainer with CheckBoxes to the container

  self.ids.cuarta_pantalla.ids.container.add_widget(BoxContainer)
  self.ids.cuarta_pantalla.ids.container.ids[f'pre_{idx+1}'] = weakref.ref(BoxContainer)

标签: pythonobjectiterationkivyweak-references

解决方案


不需要使用weakref,每次add_widget使用时,一个称为children的Observable List将包含在添加的对象中,另一个将包含该添加对象的引用。

例如:

IDlist = self.ids.cuarta_pantalla.ids.container.children

可以迭代变量IDlist以获取每个引用,您可以在其中调用该特定对象的任何方法


推荐阅读