如何引用Kivy App类属性



我遇到了引用应用程序类真实变量的问题,我是kivy 的初学者

查看此代码

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()

我只想在python代码中的任何地方使用num变量,而不是在KV代码中

感谢阅读。

我认为您的代码(至少您发布的代码(应该如您所期望的那样工作。这是您的代码的一个版本,添加了额外的代码以使其正常工作。每次按下Button时,它都会调用func,并显示预期的行为(将num作为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()

您可以在类之外定义它,使其成为全局变量,这样您就可以在.py文件或.kv文件中的任何位置使用它

最新更新