2016-10-04 81 views
0

我想在RootWidgetremove孩子小孩下面的例子中,但點擊RootButton刪除兩個孩子小部件(紅色和綠色的)。但是在shell中打印的self.children列表中仍有第二個孩子,但不在RootWidget上查看。這裏做錯了什麼?Kivy remove_widget從屏幕中刪除所有的孩子小部件

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

不確定這種行爲的確切原因是什麼。也許當你按下你的按鈕,它將從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() 
相關問題