Abhay Kumar
Abhay Kumar

Reputation: 166

How do I make my custom widget in python kivy file and use it multiple times by changing its size, pos and color?

This code is not working please correct me and guide me how to make it.

-.py file

class RLB(Widget):
    pass

class Bars(Widget):
        pass

class FGHApp(App):
    pass

FGHApp().run()

-FGH.kv file

I here wanted to make custom widget named 'RLB' and I want it to use it multiples times like any other built in widgets like button, label,..

#My custom widget
Bars:

<RLB>:
    canvas:
        Color:
            rgba:self.color
        RoundedRectangle:
            pos:self.pos
            size:self.size
            radius: [10]
<Bars>:
    FloatLayout:
        size:root.size
        RLB:
            #Error
            color:(1,0,1,1)
            pos:(100,100)
            size:(200,200)
        RLB:
            #Error
            color:(1,0,0,0.5)
            pos:(300,300)
            size:(200,200)

Upvotes: 0

Views: 404

Answers (2)

Abhay Kumar
Abhay Kumar

Reputation: 166

Finally i have done it on my own :) 1st we have to make a widget class and add all instructions on it like color,size,..This is because we can not edit widget class so we have created a copy of widget class by inheriting it

<Wp@Widget>:
    size_hint:None,None
    size:(dp(100),dp(100))
    pos:(0,0)
    color:(1,1,1,1)

Now Wp is our new widget who has all required things after this we have to make our own widget who inherits from this 'Wp' class.

<RLB@Wp>:
    canvas:
        Color:
            rgba:root.color
        RoundedRectangle:
            pos:root.pos
            size:root.size
            radius: [dp(10),]

Now its done and now we can use it any number of times by changing its color,size and positions.

<Bars>:
    FloatLayout:
        size:root.size
        RLB:
            color:(1,1,0,1)
            pos:(0,0)
            size:(100,100)
        RLB:
            color:(1,0,1,1)
            pos:(100,100)
            size:(100,100)

Now there is no need of this in .py file

#not needed
class RBL(Widget):
    pass

Upvotes: 0

Hussam F. Alkdary
Hussam F. Alkdary

Reputation: 727

you should define the property that you want to change later

class RLB(Widget):
    # you can give an initial value white for example 
    # You don't need to add pos and size properties, since Widget already has those proprties.
    color=ListProperty([1,1,1,1])


and then you should refer to this property is the kv file


<RLB>:
   # use root instead of self
    canvas:
        Color:
            rgba:root.color
        RoundedRectangle:
            pos:root.pos
            size:root.size
            radius: [10]

also you can use any kivy property from here there are a lot of them

Upvotes: 1

Related Questions