How can I reference a widget class created in kv file in Python code?

83 views
Skip to first unread message

JB

unread,
Jul 31, 2019, 9:50:29 AM7/31/19
to Kivy users support
I have created a widget in kv file which extends Label and then two more classes that add background_color or border functionality to the label. In kv file it is declared:

<BackgroundColour@Widget>:
background_color: 0, 0, 0, 0
canvas.before:
Color:
rgba: root.background_color
Rectangle:
size: self.size
pos: self.pos

<Border@Widget>:
border_color: 0, 0, 0, 0
border_width: 1
canvas.before:
Color:
rgba: root.border_color
Line:
width: root.border_width
rectangle: self.x, self.y, self.width, self.height

<MyLabel@Label+BackgroundColour+Border>

Is there a way now to reference that MyLabel class in Python code without having to move the BackgroundColour and Border functionality to Python (which I don't want to do because writing canvas.before and binding properties in Python is a pain)?


Elliot Garbus

unread,
Aug 1, 2019, 12:19:02 AM8/1/19
to kivy-...@googlegroups.com

I’m not sure I completely understand your objective, there are a number of ways to move between KV and the Python code.

I have attached a KV file and a py file.  Apologies for the colors, they were the result of random choices.

 

Key concept, you can simply declare the class in python


class BackgroundColour(Widget):
   
pass

 

and define the style in kv:

<BackgroundColour>:
   
canvas.before:
       
Color:
           
rgba: root.bg_color
       
Rectangle:
           
size: self.size
            pos
: self.pos

 

Doing this bridges the name space letting you use the names in both KV and Python. 

Let me know if the attached code answers your question.

--
You received this message because you are subscribed to the Google Groups "Kivy users support" group.
To unsubscribe from this group and stop receiving emails from it, send an email to kivy-users+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/kivy-users/d91a3024-7fec-4ab8-99ff-878e5c641c3b%40googlegroups.com.

 

testkp.kv
testkp.py

Matthew Einhorn

unread,
Aug 1, 2019, 9:58:22 PM8/1/19
to kivy-...@googlegroups.com
Additionally, you should be able to do something like `from kivy.factory import Factory` and then `label = Factory.MyLabel()` or `label = Factory.get('MyLabel')()`.

Matt

JB

unread,
Aug 2, 2019, 6:28:36 AM8/2/19
to Kivy users support
Thank you both Elliot and Matt! Elliot's solution is exactly what I needed. I didn't realise I can mix in multiple Widget classes.

To unsubscribe from this group and stop receiving emails from it, send an email to kivy-...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Kivy users support" group.
To unsubscribe from this group and stop receiving emails from it, send an email to kivy-...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages