Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove a widget in kivy?

Tags:

python

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
like image 675
victorcd Avatar asked Jul 20 '16 21:07

victorcd


People also ask

What is widget class Kivy?

The Widget class is the base class required for creating Widgets. This widget class was designed with a couple of principles in mind: Event Driven. Widget interaction is built on top of events that occur. If a property changes, the widget can respond to the change in the 'on_<propname>' callback.

What is POS hint in Kivy?

pos : pos stands for position i.e it is used to position the widget. By default (0, 0), the bottom-left corner of the screen is the default position of the button in kivy python.

What is FloatLayout Kivy?

FloatLayout honors the pos_hint and the size_hint properties of its children. For example, a FloatLayout with a size of (300, 300) is created: layout = FloatLayout(size=(300, 300))

What is GridLayout Kivy?

The GridLayout arranges children in a matrix. It takes the available space and divides it into columns and rows, then adds widgets to the resulting “cells”. Changed in version 1.0. 7: The implementation has changed to use the widget size_hint for calculating column/row sizes.


1 Answers

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)

like image 81
el3ien Avatar answered Sep 18 '22 15:09

el3ien