Search code examples
pythonkivy

How can I remove a widget in kivy?


I am trying to do the same as I did to add these widgets, but without success. I am working with the kv language and bind function. With this code below is possible add a buttons dynamically, but isn't possible remove them.

.py

class PrimeiroScreen(Screen):
    def __init__(self, **kwargs):
        self.name = 'um'
        super(Screen,self).__init__(**kwargs)


    def fc2(self):
        btn = Button(text="Botão",size_hint=(.1,.1))
        self.ids.grade2.add_widget(btn)     
        btn.bind(on_press=self.printa)

    def printa(self,*args):
        #btn2 = Button(text="Btn2",size_hint=(.1,.1))#I can add another btn succesfully
        self.ids.grade2.add_widget(btn2)#but I can do the same by this way
        self.remove_widget(btn)
        grade2.remove_widget(self.btn)

and the .kv

<RootScreen>:
    PrimeiroScreen:

<PrimeiroScreen>:
    GridLayout:
        cols: 1
        size_hint: (.5,1)
        id: grade
        Button:
            text: "hi!"
            on_press: root.fc2()

    StackLayout:
        orientation: 'bt-rl'
        GridLayout:
            cols: 2
            size_hint: (.5,1)
            id: grade2

Has anybody any idea of the mistake I made? Python shows me the message below:

self.remove_widget(btn)
NameError: global name 'btn' is not defined

Solution

  • Change
    btn = Button(text="Botão",size_hint=(.1,.1))
    to
    self.btn = Button(text="Botão",size_hint=(.1,.1))
    So you make it a class attribute.

    And then remove it like this
    self.remove_widget(self.btn)