【问题标题】:Referencing a variable from a Python file to a .kv file将 Python 文件中的变量引用到 .kv 文件
【发布时间】:2021-08-14 05:38:34
【问题描述】:

在 python Kivy 教程中,我了解到我可以将 .kv 文件中的变量引用到我的 python 文件。有没有办法反之亦然?

(将我的 Python 文件中的变量引用到它的 .kv 文件)

【问题讨论】:

    标签: python-3.x kivy kivymd


    【解决方案1】:

    我知道有很多方法可以将变量从 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 文件中引用哪个类,该标签就会发生变化。

    【讨论】:

    • 哇,这是我第一次使用堆栈溢出,我不知道它是如此活跃和有效。感谢您帮助这个 15 岁的白痴 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 2022-11-29
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    相关资源
    最近更新 更多