### main.py ###
from kivy.app import App
class MainScreen():
def button_clicked(self):
print("*")
class KivyApp(App):
pass
KivyApp().run()
### kivy.kv ###
MainScreen:
<MainScreen@BoxLayout>:
Button:
on_press: root.button_clicked()
Why I can not call button_clicked() function from kivy? I know that I can call it if describe like
class MainScreen(BoxLayout)
in main.py. But why I can not with above codes?
CodePudding user response:
So, I am not 100% sure about my answer but here is what I think is happening...
The py file runs first and then the kv file, so if in the py file you have Class MainScreen(BoxLayout):
the MainScreen class is defined and inherits from BoxLayout... Then the rules are defined in the kV file as normal. When you use the @BoxLayout
in the kV file the class is created again, so this over rides the first definition of MainScreen
. As the py MainScreen
has been over ridden by the kV MainScreen
the attribute root.button_clicked()
no longer exists....
If you really need use the @BoxLayout
in the kV file you could add the function to the app class:
class LayoutApp(App):
def button_clicked(self):
print("*")
And then in the kV file:
MainScreen:
<MainScreen@BoxLayout>:
Button:
on_press: app.button_clicked()