Kivy remove_widget从屏幕上删除所有子窗口小部件

时间:2016-10-04 08:42:44

标签: python-2.7 kivy

我希望在下面的示例中使用remove中的RootWidget子窗口小部件,但是单击RootButton会删除两个子窗口小部件(RED和GREEN窗口小部件)。但是在shell中打印的self.children列表中仍然存在第二个子节点,但不能在RootWidget上看到。这里有什么问题?

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout

RED = (1, 0, 0, 1)
GREEN = (0, 1, 0, 1)

class RootWidget(Button):

    def __init__(self, *args, **kwargs):
        super(RootWidget, self).__init__(*args, **kwargs)
        self.add_widget(Button(background_color = RED), 0)
        self.add_widget(Button(background_color = GREEN), 1)
        self.bind(on_press = self.btn_call_back)

    def btn_call_back(self, v):
        try:
            print "_" * 60
            print self.children
            print "+" * 60
            self.remove_widget(self.children[0])
            print self.children
            print "_" * 60
        except IndexError:
            print "no children any more!"




class TutorApp(App):

    def build(self):
        return RootWidget()


if __name__ == "__main__":
    TutorApp().run()

1 个答案:

答案 0 :(得分:1)

不确定这种行为的确切原因是什么。也许当您按下按钮并将其背景从background_normal替换为background_down时,这会以某种方式覆盖其子项的背景。这没关系,因为您不应该将小部件添加到Button实例。请改用Widget或某些布局类来排列小部件。

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

Builder.load_string('''
<Widget>:
    canvas.before:
        Color:
            rgb: 0, 0, 1
        Rectangle:
            size: self.size
            pos: self.pos
''')

RED = (1, 0, 0, 1)
GREEN = (0, 1, 0, 1)

class RootWidget(Widget):

    def __init__(self, *args, **kwargs):
        super(RootWidget, self).__init__(*args, **kwargs)
        self.add_widget(Button(background_color = RED), 0)
        self.add_widget(Button(background_color = GREEN), 1)
        self.bind(on_touch_down = self.btn_call_back)


    def btn_call_back(self, *args):
        try:
            print "_" * 60
            print self.children
            print "+" * 60
            self.remove_widget(self.children[0])
            print self.children
            print "_" * 60
        except IndexError:
            print "no children any more!"


class TutorApp(App):
    def build(self):
        return RootWidget()


if __name__ == "__main__":
    TutorApp().run()