Search code examples
classkivyrootparentkivy-language

Organizing kivy layout(s) and classes


I have a rather large App split in a single .kv file and a GUI.py file accessing a library of other .py files. I came to a point where i want to organize everything and split up large layouts into different classes and .kv files.

Currently im working on a function which should add and remove a certain layout to my main layout while still accessing variables and functions of the base class (called BoxL). I tried various things, but i dont know how i can hand over/instantiate my main class to/in my new class.

Im trying to build a rough minimal example:

Main python file: GUI.py

import kivy
from kivy.app import App
from kivy.config import Config
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

class AdvancedClass(BoxLayout):
"""This is my new class from which i want to access BoxL class."""
    pass

class BoxL(BoxLayout):
    def __init__(self):
        super(BoxL, self).__init__()

    some_variable = 1
    advanced_mode_enabled = False

    def some_function(self):
        print(self.some_variable)
        print('Im also doing stuff in GUI.kv file with ids')
        self.ids.test_label.text = '[b]some text with markup'

    def advanced_mode(self):
        if not self.advanced_mode_enabled:
            print('Enabling advanced mode ..')
            self.ids.master_box.add_widget(self.advanced_class_obj)
            self.advanced_mode_enabled = True
        else:
            print('Disabling advanced mode ..')
            self.ids.master_box.remove_widget(self.advanced_class_obj)
            self.advanced_mode_enabled = False

class GUI(App):
    def build(self):
        Builder.load_file('layouts.kv')  # i read its best to instanciate kivy files here once everything is loaded
        BoxL.advanced_class_obj = AdvancedClass()

if __name__ == "__main__":
    GUI().run()

Main layout file: GUI.kv

<BoxL>:
    orientation: 'vertical'
    id: master_box
    Label:
        text: str(root.some_variable)
    Button:
        text: 'Change variable'
        on_release:
            root.some_variable = 2
    Button:
        text: 'Add advanced layout'
        on_release:
            root.advanced_mode(self)

New layout file layouts.kv from which i want to access functions/variables of BoxL class in GUI.py:

<AdvancedClass>:
    orientation: 'vertical'
    Label:
        text: '[b]TEST'
    TextInput:
        hint_text: 'TEST'
    Button:
        text: 'KLICK'
        on_release:
            # print(parent.some_variable)
            # print(self.some_variable)
            # print(BoxL.some_variable)
            print('Im not sure how to do this .. ')  # issue-point

I hope this covers everything. Im struggling with this for quite a while.


Solution

  • Figured it out: app.root.FUNCTION()