Daniel Daniel - 1 month ago 16
Python Question

Kivy object doesn't render when defined in .kv file

I'm developing an app in kivy and currently trying to figure out why I can get an object to render when I add it in Python but not in the .kv file.

This works fine, rendering the background image with a switch on top of it.

class LoginScreen(Screen):
def __init__(self,**kwargs):
super(LoginScreen, self).__init__(**kwargs)
self.layout = BoxLayout(orientation='vertical')
self.add_widget(self.layout)
self.layout.add_widget(defSwitch())
def on_touch_up(self,touch):
if self.collide_point(*touch.pos):
self.parent.current = 'data'

class defSwitch(Switch):
active = False


Where the .kv file is:

<LoginScreen>:
imgname: './images/' + 'login.jpg'
canvas.before:
Rectangle:
pos: self.pos
size: self.size
source: self.imgname


This doesn't render anything but the background image:

class LoginScreen(Screen):
def on_touch_up(self,touch):
if self.collide_point(*touch.pos):
self.parent.current = 'data'

class defSwitch(Switch):
active = False


where in this case the .kv file has:

<LoginScreen>:
imgname: './images/' + 'login.jpg'
canvas.before:
Rectangle:
pos: self.pos
size: self.size
source: self.imgname
BoxLayout:
orientation: 'vertical'
defSwitch:


If I replace defSwitch: in the .kv file by a default Switch object, then it renders fine. Why can't I use a custom object?

Answer

If you want to use a custom class created in .py file with kv language, you need to set it in .kv file too:

<defScreen>:    # class def

<LoginScreen>:
    ...
    defScreen:  # object

so that it knows what to look for.

Also I'd like to recommend you using camel case in kv language as there are situations in which the parser won't recognize the phrase as a widget.