简体   繁体   English

如何在Kivy的.kv文件中添加ID?

[英]How to add an id in Kivy's .kv file?

I'm struggling to come up with a simple example for using IDs. 我正在努力提出一个使用ID的简单示例。 Later I want to use the IDs to change parameters, for instance to change the text in a label or a button. 稍后,我想使用ID来更改参数,例如,更改标签或按钮中的文本。 So how do I get started? 那我该如何开始呢? I can't find simple example for using IDs. 我找不到使用ID的简单示例。

import kivy
from kivy.uix.gridlayout import GridLayout
from kivy.app import App

class TestApp(App):
    pass

if __name__ == '__main__':
    TestApp().run()

The .kv file: .kv文件:

#:kivy 1.0

Button:
    text: 'this button \n is the root'
    color: .8, .9, 0, 1
    font_size: 32

    Label: 
        text: 'This is a label'
        color: .9, 0, .5, .5

In this case I would like to use an ID for the label and be able to change the text. 在这种情况下,我想为标签使用ID并能够更改文本。

You can find some info about the kv language here . 您可以在此处找到有关kv语言的一些信息。 You need to use kivy properties for that. 您需要为此使用kivy属性

here is an example on how you can change the label text when you press the button: python file: 这是一个有关如何在按下按钮时更改标签文本的示例:python文件:

import kivy
from kivy.uix.gridlayout import GridLayout
from kivy.app import App
from kivy.properties import ObjectProperty

class GridScreen(GridLayout):
    label = ObjectProperty() #accessing the label in python
    def btnpress(self):
        self.label.text = 'btn pressed' #changing the label text when button is pressed

class TestApp(App):
    def build(self):
        return GridScreen()

if __name__ == '__main__':
    TestApp().run()

kv file: kv文件:

<GridScreen>:
    label: label #referencing the label
    rows: 2
    Button:
        text: 'this button \n is the root'
        color: .8, .9, 0, 1
        font_size: 32
        on_press: root.btnpress() #calling the method 

    Label:
        id: label
        text: 'This is a label'
        color: .9, 0, .5, .5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM