Only one root object is allowed by .kv error

135 views
Skip to first unread message

Deven Deshpande

unread,
Oct 1, 2021, 11:51:20 PM10/1/21
to Kivy development
Hi , I am an Indian game developer . I have just started to learn kivy . I followed the tutorial of freecodecamp.org . I tried to make a button but I am facing this error of Only one root object is allowed by .kv. Here is my code . 
Main.py 
from kivy.app import App
from kivy.uix.widget import Widget


class MainWidget(Widget):
pass
class TheLabApp(App):
pass

TheLabApp().run()

TheLab.kv 
MainWidget:
<MainWidget>:
Button:
text: "Hello"

Regards, Deven Deshpande 

Lusayo Nyondo

unread,
Nov 16, 2021, 4:52:26 AM11/16/21
to Kivy development
Hi.

Sorry for the late reply. I am new to this group myself.

At the very base of the file, kv files allow you to define two types of rules. Class rules and root rules.
You can think of a class rule as, well, a class, and a root rule as an object of that class. If you define properties within a class rule, your properties apply to all instances of that class used throughout your kv file. Class rules follow the syntax:

<ClassName>:
    # Enter properties here

For a root rule, the properties only apply to that particular instance of the class. A kv file can only have one root rule. Root rules for the syntax:

ClassName:
    # Enter properties here

Note that for a root rule, there are not opening and closing tags. That is essentially where your problem is. You cannot declare both the Button and MainWidget widgets as root widgets because kivy only renders one root widget per file. Since Button and MainWidget both don't have tags, kivy treats them both as root widgets. To get rid of that error, make Button a class rule like so:

MainWidget:
    <MainWidget>:
Button:
    text: "Hello"



Reply all
Reply to author
Forward
0 new messages