I started learning how to use kivy today and it won't run, can someone help? here is my code:
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
class ChildApp(GridLayout):
def __init__(self, **kwargs):
super(ChildApp, self).__init__()
self.cols = 2
self.add_widget(Label(text="Student name: "))
self.s_name = TextInput()
self.add_widget(self.s_name)
self.add_widget(Label(text="Student gender: "))
self.s_gender = TextInput()
self.add_widget(self.s_gender)
self.add_widget(Label(text="Student Marks: "))
self.s_marks = TextInput()
self.add_widget(self.s_marks)
class ParentApp(App):
def build(self):
App.root = ChildApp
return App.root
if __name__ == "__main__":
ParentApp().run()
and this is the error that pops up:
[CRITICAL] App.root must be an _instance_ of Widget
Traceback (most recent call last):
File "C:\Users\admin\kivyLab\app.py", line 32, in <module>
ParentApp().run()
File "C:\Users\admin\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\app.py", line 949, in run
self._run_prepare()
File "C:\Users\admin\AppData\Local\Programs\Python\Python39\lib\site-packages\kivy\app.py", line 925, in _run_prepare
raise Exception('Invalid instance in App.root')
Exception: Invalid instance in App.root
Process finished with exit code 1
what did I do wrong? In the tutorials that I watched the code worked fine with no errors so I dont know what I did wrong
CodePudding user response:
You shouldn't really set App.root directly, the normal api is to return your intended root widget from the build method.
The specific problem is you set App.root to ChildApp instead of ChildApp(), i.e. you used the class itself instead of an instance of the class.
CodePudding user response:
Try using kivy's Builder to load a string in the kivy lang:
from kivy.app import App
from kivy.lang import Builder
kv = """
Screen:
GridLayout:
cols: 2
rows:2
Label:
text:"Student name: "
TextInput:
id:s_name
Label:
text:"Student gender: "
TextInput:
id:s_gender
"""
class ParentApp(App):
screen = None
def build(self):
self.screen = Builder.load_string(kv)
return self.screen
if __name__ == "__main__":
ParentApp().run()
As you can see it is a lot simpler and easier to read. Comment below if any problems.
