如何在Kivy文件中访问全局变量? [英] How to access a global var in Kivy file?
本文介绍了如何在Kivy文件中访问全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为Tiles的全局变量,想将TreasureHuntGrid类中的cols数量设置为kivy文件.
I have a global variable called Tiles and want to set the number of cols in the TreasureHuntGrid class to the kivy file.
Main.py
Tiles = 5
class TreasureHuntGrid(GridLayout):
global Tiles
.kv
<TreasureHuntGrid>:
cols: #Don't know what should I put in here
推荐答案
全局是邪恶的一个>.如果要从任何小部件访问变量,最好将其放入Application
类,因为程序中将只有一个实例:
Globals are evil. If you want to have a variable accessible from any widget it's better to put it into the Application
class, since you will only have one instance in your program:
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()
话虽如此,如果您确实需要的话,可以访问这样的全局变量:
Having said that, you can access global variables like this if you really need that:
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()
这篇关于如何在Kivy文件中访问全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文