如何访问 Kivy 文件中的全局变量?
How to access a global var in Kivy file?
我有一个名为 Tiles 的全局变量,我想将 TreasureHuntGrid class 中的列数设置到 kivy 文件中。
Main.py
Tiles = 5
class TreasureHuntGrid(GridLayout):
global Tiles
.kv
<TreasureHuntGrid>:
cols: #Don't know what should I put in here
Globals are evil。如果您想从任何小部件访问变量,最好将其放入 Application
class,因为您的程序中只有一个实例:
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder
Builder.load_string("""
<MyWidget>:
cols: app.tiles
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
""")
class MyWidget(GridLayout):
pass
class MyApp(App):
tiles = 5
def build(self):
return MyWidget()
if __name__ == '__main__':
MyApp().run()
话虽如此,如果您确实需要,您可以像这样访问全局变量:
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder
tiles = 5
Builder.load_string("""
#: import tiles __main__.tiles
<MyWidget>:
cols: tiles
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
""")
class MyWidget(GridLayout):
pass
class MyApp(App):
def build(self):
return MyWidget()
if __name__ == '__main__':
MyApp().run()
我有一个名为 Tiles 的全局变量,我想将 TreasureHuntGrid class 中的列数设置到 kivy 文件中。
Main.py
Tiles = 5
class TreasureHuntGrid(GridLayout):
global Tiles
.kv
<TreasureHuntGrid>:
cols: #Don't know what should I put in here
Globals are evil。如果您想从任何小部件访问变量,最好将其放入 Application
class,因为您的程序中只有一个实例:
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder
Builder.load_string("""
<MyWidget>:
cols: app.tiles
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
""")
class MyWidget(GridLayout):
pass
class MyApp(App):
tiles = 5
def build(self):
return MyWidget()
if __name__ == '__main__':
MyApp().run()
话虽如此,如果您确实需要,您可以像这样访问全局变量:
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder
tiles = 5
Builder.load_string("""
#: import tiles __main__.tiles
<MyWidget>:
cols: tiles
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
Label:
text: "test"
""")
class MyWidget(GridLayout):
pass
class MyApp(App):
def build(self):
return MyWidget()
if __name__ == '__main__':
MyApp().run()