Kivy class in .py and .kv interaction
I don't quite understand how the classes in the python and kiwi file interact. I am currently modifying the Kivy Showcase example to increase my understanding.
File structure
- main.py
- showcase.kv
- Data / screens / test.kv
main.py
class Testy(BoxLayout):
ttext = 'Bla'
#other code
class ShowcaseScreen(Screen):
fullscreen = BooleanProperty(False)
def add_widget(self, *args):
if 'content' in self.ids:
return self.ids.content.add_widget(*args)
return super(ShowcaseScreen, self).add_widget(*args)
class ShowcaseApp(App):
#code
test.kv
<Testy>:
orientation: 'vertical'
Label:
text: root.ttext
ShowcaseScreen:
name: 'LearnKanji'
fullscreen: True
#Some ref to <Testy>
Question
I want to have my code in Testy () because I plan to write a lot of code targeting what is happening on that one screen, and I don't want to clutter up ShowcaseScreen () because ShowcaseScreen also means for other screens.
To clarify, in test.kv I mean the ttext variable. If I hadn't made the Testy () class, I would have said the following:
ShowcaseScreen:
name: 'LearnKanji'
fullscreen: True
BoxLayout:
text: root.ttext
And then in main.py I will need to put
class ShowcaseScreen(Screen):
ttext = 'Bla'
However, since many screens other than Testy use the ShowcaseScreen () class, so all the code for all screens will be too large here. So I want the code to screen in a separate class. I think this is the best way for larger code projects.
So how can I reference after calling ShowcaseScreen: in the test.kv file? So I can put the code for Testy in Testy () and keep my files and classes more organized.
Next question: Kivy class in .py and .kv interaction 2
source to share
You can use ScreenManager
. Take a look here, I've modified some of your code to provide an example of using the ScreenManager to split the code for each screen into its own classes. If there are any problems with this, let me know.
main.py
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.properties import ObjectProperty
class Testy(Screen):
ttext = 'Screen 2'
#other code
class ScreenTwo(Screen):
pass
class Manager(ScreenManager):
testy = ObjectProperty(None)
screen_2 = ObjectProperty(None)
class ShowcaseApp(App):
def build(self):
return Manager(transition=FadeTransition())
if __name__ == "__main__":
ShowcaseApp().run()
kv file:
<Testy>:
BoxLayout:
Button:
text: root.ttext
on_press: root.manager.current = "screen_two"
<ScreenTwo>:
BoxLayout:
Button:
text: "Screen 1"
on_press: root.manager.current = "testy_screen"
<Manager>:
id: screen_manager
testy: testy
screen_2: screen_2
Testy:
id: testy
name: 'testy_screen'
manager: screen_manager
ScreenTwo:
id: screen_2
name: 'screen_two'
manager: screen_manager
source to share