我想访问 child 的 id 来决定是否删除小部件。我有以下代码:
主要.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()
测试.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
? - 如何检查我没有删除带有“删除”的按钮,而是删除所有其他按钮?
最佳答案
正如您在 documentation 中所读到的那样:
In a widget tree there is often a need to access/reference other widgets. The Kv Language provides a way to do this using id’s. Think of them as class level variables that can only be used in the Kv language.
描述了从 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()
要跳过删除带有“删除”标签的按钮,您可以检查其 text
属性。但是从循环内部删除会导致错误,因为在您迭代的列表将被更改后,一些子项将被跳过:
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)
关于python - kivy 访问 child ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31639452/