我想访问孩子的id来决定是否删除小部件。我有以下代码:
main.py
#!/usr/bin/kivy
# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
class Terminator(BoxLayout):
def DelButton(self):
print("Deleting...")
for child in self.children:
print(child)
print(child.text)
if not child.id == 'deleto':
print(child.id)
#self.remove_widget(child)
else:
print('No delete')
class TestApp(App):
def build(self):
pass
if __name__ == '__main__':
TestApp().run()
test.kv
#:kivy 1.9.0
<Terminator>:
id: masta
orientation: 'vertical'
Button:
id: deleto
text: "Delete"
on_release: masta.DelButton()
Button
Button
Terminator
但是,当使用print(child.id)
打印ID时,它始终返回:None
。即使print(child.text)
正确返回Delete
或。
child.id
不会返回deleto
,而是None
?答案 0 :(得分:3)
您可以阅读documentation:
在窗口小部件树中,通常需要访问/引用其他树 小部件。 Kv语言提供了一种使用id的方法。认为 它们作为只能在Kv中使用的类级别变量 语言。
描述了Python代码中的访问ID here。工作示例:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.properties import ObjectProperty
from kivy.uix.button import Button
Builder.load_string("""
<Terminator>:
id: masta
orientation: 'vertical'
MyButton:
id: deleto
button_id: deleto
text: "Delete"
on_release: masta.DelButton()
MyButton
MyButton
""")
class MyButton(Button):
button_id = ObjectProperty(None)
class Terminator(BoxLayout):
def DelButton(self):
for child in self.children:
print(child.button_id)
class TestApp(App):
def build(self):
return Terminator()
if __name__ == '__main__':
TestApp().run()
要跳过删除按钮&#34;删除&#34;标签,您可以检查其text
属性。从循环内部删除Hovewer将导致错误,因为一些孩子将在你重复的列表之后被改变:
class Terminator(BoxLayout):
def DelButton(self):
for child in self.children:
self.remove_widget(child) # this will leave one child
您必须创建要删除的子项列表:
class Terminator(BoxLayout):
def DelButton(self):
for child in [child for child in self.children]:
self.remove_widget(child) # this will delete all children
在你的情况下:
class Terminator(BoxLayout):
def DelButton(self):
for child in [child for child in self.children if child.text != "Delete"]:
self.remove_widget(child)