我有一个名为Tiles的全局变量,并希望将TreasureHuntGrid类中的cols数设置为kivy文件。
Main.py
Tiles = 5
class TreasureHuntGrid(GridLayout):
global Tiles
.kv
<TreasureHuntGrid>:
cols: #Don't know what should I put in here
答案 0 :(得分:4)
Globals are evil。如果您希望从任何窗口小部件访问变量,最好将其放入Application
类,因为您的程序中只有一个实例:
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()