【发布时间】:2021-08-14 05:38:34
【问题描述】:
在 python Kivy 教程中,我了解到我可以将 .kv 文件中的变量引用到我的 python 文件。有没有办法反之亦然?
(将我的 Python 文件中的变量引用到它的 .kv 文件)
【问题讨论】:
标签: python-3.x kivy kivymd
在 python Kivy 教程中,我了解到我可以将 .kv 文件中的变量引用到我的 python 文件。有没有办法反之亦然?
(将我的 Python 文件中的变量引用到它的 .kv 文件)
【问题讨论】:
标签: python-3.x kivy kivymd
我知道有很多方法可以将变量从 python 引用到 kivy。但是我在我的应用程序中所做的只是在一个类中创建一个变量,然后在 kivy 文件中调用它。你可以在这段代码中看到它。
Python main.py 文件:
from kivy.app import App
from kivy.uix import BoxLayout
class Window(BoxLayout):
class_var = "This is the value that will reference from the Window class"
class KivyApp(App):
app_var = 'This is the value reference from the variable in class App'
def build(self):
return Window()
if __name__ == '__main__':
KivyApp().run()
kivy kivy.kv 文件
<Window>:
orientation: 'vertical'
padding: [20]
Label:
id: lbl
text: 'Sample Text'
Button:
text: 'Reference from Window Class'
on_release: lbl.text = root.class_var
# root is use to reference from the root class if you need to reference a variable from another class you can use app or the name of the other class.
Button:
text: 'Reference from App Class'
on_release: lbl.text = app.app_var
在这个程序中,您将在顶部有一个标签,一旦您按下按钮,您希望它在 python 文件中引用哪个类,该标签就会发生变化。
【讨论】: