Kivy-按ID删除小部件 [英] Kivy - Removing widget by id

查看:72
本文介绍了Kivy-按ID删除小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout


class GUI(FloatLayout):
    def remove(self):
        self.remove_widget(self.ids.test)


class GUIApp(App):
    def build(self):
        return GUI()


if __name__ == '__main__':
    GUIApp().run()

以及相应的kv文件:

#:kivy 1.9.1

<GUI>:
    BoxLayout:
        Button:
            id: test
            text: 'Test'
            on_press: root.remove()

单击该按钮应将其删除.但是,这不会发生.如果删除kv文件中的BoxLayout,则程序将按预期方式工作,并且该按钮也将被删除.为什么会发生这种情况,如何删除在kv文件中声明的小部件? (我知道我可以用self.parent.remove_widget(self)替换Button的on_press,但是除了删除小部件外,我在root.remove()中也有代码.)

The button should be removed when clicked. However, this does not happen. If I remove the BoxLayout in the kv file, the program works as expected, and the button is removed. Why does this happen, and how can I remove a widget declared in a kv file? (I know I can replace the Button's on_press with self.parent.remove_widget(self), but I have code in root.remove() besides removing the widget.)

推荐答案

实际上,当按钮的父级实际上位于BoxLayout中时,您正在调用GUI对象的remove_widget. remove_widget仅删除直接子级,而不删除任何后代.

You're calling remove_widget of GUI object when your button's parent is actually BoxLayout inside it. remove_widget only deletes a direct children, not any descendant.

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder

Builder.load_string('''
<GUI>:
    BoxLayout:
        id: layout
        Button:
            id: test
            text: 'Test'
            on_press: root.remove()
''')


class GUI(FloatLayout):
    def remove(self):
        self.ids.layout.remove_widget(self.ids.test)


class GUIApp(App):
    def build(self):
        return GUI()


if __name__ == '__main__':
    GUIApp().run()

这篇关于Kivy-按ID删除小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆