Search code examples
pythonkivy

How to address remove_widget what widget to remove inside another layout in Kivy


I am a beginner just learning coding and Python. I am not able to remove a widget that I just have created.

I can still create new button. This is actually just little side test.

Eventually I want to have a scrollview where I can add and remove buttons. There are some add/remove widget code snippets but I must be able to add/remove widgets in another layout.

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

KV = """
BoxLayout
    id:aaa
    Button
        text: 'Add'
        on_press: app.add_more()
        
    Button:
        text:'Remove'
        on_press: app.remove()
    BoxLayout:
        id:abc

"""

class MyApp(App):
    def build(self):
        self.root = Builder.load_string(KV)

    def add_more(self):
        print('wass')
        addbutton = self.root.ids.abc
        addbutton.add_widget(Button(text='hello'))

    def remove(self):
        print('hello')
        self.remove_widget(self.children[0])

MyApp().run()

I got this error message when clicking the remove button:

MyApp' object has no attribute 'remove_widget'


Solution

  • AttributeError

         self.remove_widget(self.children[0])
     AttributeError: 'MyApp' object has no attribute 'remove_widget'
    

    Root Cause

    The App class inherited by MyApp, does not have the method, remove_widget(). Only a root widget, which usually has children that can have children of their own.

    Question

    remove widget inside another layout

    Solution

    • Replace self.remove_widget(...) to self.root.ids.abc.remove_widget(...)
    • Replace self.children[0] with self.root.ids.abc.children[0]
    • Check that there are children inside the layout before we invoke remove_widget()

    Snippets

    def remove(self):
        print('hello')
        if len(self.root.ids.abc.children) > 0:   # check for children
            self.root.ids.abc.remove_widget(self.root.ids.abc.children[0])  # remove child FIFO
    

    Kivy Widget » remove_widget()

    Widgets in Kivy are organized in trees. Your application has a root widget, which usually has children that can have children of their own. Children of a widget are represented as the children attribute, a Kivy ListProperty.

    The widget tree can be manipulated with the following methods:

    add_widget(): add a widget as a child
    remove_widget(): remove a widget from the children list
    clear_widgets(): remove all children from a widget