简体   繁体   中英

How to reference Kivy App class attributes

I stuck at a problem of referencing app class real variable, I am a beginner in kivy

see this code

class Screen_mgr(ScreenManager):
    pass

class MainScreen(Screen):
    def func(self):
        if(SimpleApp.num == 0): #this statement always returns True as num is always 0 in app class
            SimpleApp.num +=10 #How can I access the num variable of app class

class SimpleApp(MDApp):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        self.theme_cls.theme_style = "Dark"

    num = NumericProperty(0)
    def build(self):
        return Screen_mgr()

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

I want to use that num variable everywhere in python code only Not in KV code.

Thanks For Reading.

You can define it outside of your class that will make it a global variable so you can use it everywhere in your.py file or.kv file

I think your code (at least what you posted of it) should work as you expect. Here is a version of your code, with additional code just to make it work. The Button calls the func every time you press it, and it shows the expected behavior (with num as a NumericProperty ):

from kivy.lang import Builder
from kivy.properties import NumericProperty
from kivy.uix.screenmanager import ScreenManager, Screen
from kivymd.app import MDApp


class Screen_mgr(ScreenManager):
    pass


class MainScreen(Screen):
    def func(self):
        app = MDApp.get_running_app()
        print(app.num)
        if(app.num == 0): #this statement always returns True as num is always 0 in app class
            app.num +=10 #How can I access the num variable of app class


Builder.load_string('''
<Screen_mgr>:
    MainScreen:
        id: main
        name: 'main'
        Button:
            text: 'doit'
            on_release: main.func()
''')


class SimpleApp(MDApp):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        self.theme_cls.theme_style = "Dark"

    num = NumericProperty(0)

    def build(self):
        return Screen_mgr()


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM