Anyone know how to pass an argument defined in a kivy script to a class?

Viewed 26

I have two scripts called "test_1.py" and "widgets_1.py". The first one is the main app that uses the standard widgets created in the second script to draw the main app. There is something I am missing because I expected to get a green background (admin = "user") but I didn't.

I looks like MyLabel is created with kivy default values and later on changes its values because I get the screen with the right line_color and line_width stated in "test_1.py".

Anyone knows the right way to pass admin property when initiating the widget from kivy language?

PS. This is a reduced example and being admin or not is used for other purposes than changing the background.

test_1.py:

import kivy
kivy.require('1.10.0')
import widgets_1 
from kivymd.app import MDApp
from kivymd.uix.screen import MDScreen
from kivymd.uix.boxlayout import MDBoxLayout
from kivy.lang import Builder

Builder.load_string("""
<MyBox>:
    MyLabel:
        admin: "user"
        line_color: "blue"
        line_width: 5

""")

class MyBox(MDBoxLayout):
    pass

class MainApp(MDApp):
    def build(self):
        self.screen = MDScreen()
        self.box = MyBox()
        self.screen.add_widget(self.Box)
        return self. Screen

if __name__ == "__main__":
    app = MainApp()
    app.run()

widgets_1.py:

import kivy
kivy.require('1.10.0')
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.properties import StringProperty
from kivymd.uix.boxlayout import MDBoxLayout

class MyLabel(MDBoxLayout):
    admin = StringProperty()
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        print("admin", self.admin)
        if self.admin == "user":
            self.md_bg_color = "green"
        else:
            self.md_bg_color = "red"

Thanks!

1 Answers

You can use an on_admin() method to execute some code whenever the admin property changes. Try redefining your MyLabel class as :

class MyLabel(MDBoxLayout):
    admin = StringProperty()

    def on_admin(self, instance, new_value):
        print("admin", self.admin)
        if self.admin == "user":
            self.md_bg_color = (0,1,0,1)
        else:
            self.md_bg_color = (1,0,0,1)

or, another approach is to just put the logic in the kv:

<MyBox>:
    MyLabel:
        admin: "user"
        line_color: "blue"
        line_width: 5
        md_bg_color: (0,1,0,1) if self.admin == 'user' else (1,0,0,1)

and then the on_admin() method is not needed.

Related