kivy访问子id

2024-05-01 04:04:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我想访问孩子的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()

在试验电压在

^{pr2}$

但是,当用:print(child.id)打印id时,它总是返回:None。即使print(child.text)正确返回Delete或{}不返回deleto,而是{}?在

  • 我如何检查我不删除带有“delete”的按钮,而是删除所有其他按钮?在

  • Tags: textfromimportselfidchildappif
    1条回答
    网友
    1楼 · 发布于 2024-05-01 04:04:52

    正如您在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()
    

    要跳过删除带有“Delete”标签的按钮,可以检查其text属性。从循环内部删除Hovewer将导致错误,因为在您迭代的列表更改后,某些子项将被跳过:

    ^{pr2}$

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

    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)
    

    相关问题 更多 >