kivy访问孩子id

Num*_*uis 3 python kivy

我想访问孩子的 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()
Run Code Online (Sandbox Code Playgroud)

测试.kv

#:kivy 1.9.0

<Terminator>:
    id: masta
    orientation: 'vertical'

    Button:
        id: deleto
        text: "Delete"
        on_release: masta.DelButton()

    Button
    Button

Terminator
Run Code Online (Sandbox Code Playgroud)

但是,当使用:打印 id 时print(child.id),它总是返回:None。即使print(child.text)正确返回Delete .

问题

  • 为什么child.id不返回deleto,而是相反None
  • 如何检查是否删除带有“删除”的按钮,而是删除所有其他按钮?

Nyk*_*kin 5

正如您可以在文档中阅读的那样:

\n\n
\n

在小部件树中,通常需要访问/引用其他小部件。Kv 语言提供了一种使用 id\xe2\x80\x99s 来执行此操作的方法。将它们视为只能在 Kv\n 语言中使用的类级别变量。

\n
\n\n

这里描述了从 Python 代码访问 ids。工作示例:

\n\n
from kivy.app import App\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.lang import Builder\nfrom kivy.properties import ObjectProperty\nfrom kivy.uix.button import Button\n\nBuilder.load_string("""\n<Terminator>:\n    id: masta\n    orientation: \'vertical\'\n\n    MyButton:\n        id: deleto\n\n        button_id: deleto\n\n        text: "Delete"\n        on_release: masta.DelButton()\n\n    MyButton\n    MyButton\n""")\n\nclass MyButton(Button):\n    button_id = ObjectProperty(None)\n\nclass Terminator(BoxLayout):\n    def DelButton(self):\n        for child in self.children:\n            print(child.button_id)       \n\nclass TestApp(App):\n    def build(self):\n        return Terminator()    \n\nif __name__ == \'__main__\':\n    TestApp().run()\n
Run Code Online (Sandbox Code Playgroud)\n\n

要跳过删除带有“删除”标签的按钮,您可以检查其text property. Hovewer deleting from inside the loop will lead to the bugs, since some of the children will get skiped after the list you\'re iterating on will get altered:

\n\n
class Terminator(BoxLayout):\n    def DelButton(self):\n        for child in self.children:            \n            self.remove_widget(child) # this will leave one child\n
Run Code Online (Sandbox Code Playgroud)\n\n

您必须创建要删除的子项列表:

\n\n
class Terminator(BoxLayout):\n    def DelButton(self):\n        for child in [child for child in self.children]:            \n            self.remove_widget(child) # this will delete all children\n
Run Code Online (Sandbox Code Playgroud)\n\n

在你的情况下:

\n\n
class Terminator(BoxLayout):\n    def DelButton(self):\n        for child in [child for child in self.children if child.text != "Delete"]:            \n            self.remove_widget(child)\n
Run Code Online (Sandbox Code Playgroud)\n