您想要访问其他类中的变量。有时,这可能很烦人,您可以用所有
__init__()内容和所有内容中的困难方法来完成它,或者…出现一种更简单的方法:是
get_running_app()。
您可以创建字典或其他内容,在其中可以存储其他类需要访问的任何值。这与使用类似,
globals并且花费更少的代码行。例如,在您的情况下,您可以使用字典(或嵌套字典,json,…)进行存储,例如
'checkboxes':'<namesof checked ones>',在每个init中,您可以循环这些值以创建复选框
active
基本上,您只需要在
a = App.get_running_app()某个主类-App-类中访问某个内容。
例:
from kivy.app import Appfrom kivy.lang import Builderfrom kivy.uix.screenmanager import ScreenManager, ScreenBuilder.load_string('''<Root>: MainScreen: name: 'main' AnotherScreen: name: 'another'<MainScreen>: BoxLayout: Button: text: 'next screen' on_release: root.parent.current='another' Button: text: 'ping!' on_release: root.ping()<AnotherScreen>: BoxLayout: Button: text: 'previous screen' on_release: root.parent.current='main' Button: text: 'ping!' on_release: root.ping()''')class MainScreen(Screen): def __init__(self, **kw): super(MainScreen, self).__init__(**kw) self.a = App.get_running_app() def ping(self): print self.a.big_dict['hi']class AnotherScreen(Screen): def ping(self): b = App.get_running_app() print b.big_dict['hi']class Root(ScreenManager): passclass SimpleKivy(App): big_dict={'hi':'hi there!'} def build(self): return Root()SimpleKivy().run()您会看到不需要调用
__init__(),如果真的不需要,则无需编写更多代码。



