简体   繁体   English

如何像 Kivy 中的 CSS 一样按类名选择小部件?

[英]How to select widgets by class name like in CSS in Kivy?

For example I want to put a background color to all the buttons in the application :例如,我想为应用程序中的所有按钮添加背景颜色:

<Layout1>:
    <BoxLayout>:
        <Button>:
            text: "btn 1"
        <Button>:
            text: "btn 2"
        <Button>:
            text: "btn 3"
    <Button>:
        text: "Another button outside the boxlayout"

<Layout2>:
    <GridLayout>:
        cols: 2
        <Button>:
            text: "btn 1 in a grid"
        <Button>:
            text: "btn 2 in a grid"

But I don't want to do that by hand for all of them like this :但我不想像这样为所有人手工完成:

...
    <Button>:
        text: "btn 1"
        background_color: (1, 0, 0, 1)
    <Button>:
        text: "btn 2"
        background_color: (1, 0, 0, 1)
    <Button>:
        text: "btn 3"
        background_color: (1, 0, 0, 1)
...

So I'm looking for a shorter way like if we can put a class like in CSS to all of the buttons and access them by the class name.所以我正在寻找一种更短的方法,比如我们是否可以将 CSS 中的类放在所有按钮上并通过类名访问它们。 Something like that :类似的东西:

...
    <Button>:
        text: "btn 1"
        class: "btn_class"
    <Button>:
        text: "btn 2"
        class: "btn_class"
    <Button>:
        text: "btn 3"
        class: "btn_class"
...

And in python code :在 python 代码中:

for btn in get_widgets_by_classname("btn_class") :
    btn.background_color = (1, 0, 0, 1)

In the documentation https://kivy.org/doc/stable/api-kivy.lang.html#overview it says :在文档https://kivy.org/doc/stable/api-kivy.lang.html#overview 中它说:

You can target a specific class of widgets (similar to the CSS concept of a class) by using the cls attribute (eg cls=MyTestWidget)您可以使用 cls 属性(例如 cls=MyTestWidget)定位特定类的小部件(类似于类的 CSS 概念)

but it's not that clear for me about the use of the cls attribute.但我对 cls 属性的使用不是很清楚。

Good day.再会。 In kvlang, you have two options for creating template widgets.在 kvlang 中,您有两个选项来创建模板小部件。

  1. Create a Custom Widget:创建自定义小部件:

Custom Widgets allows you to create a new, defined widget.自定义小部件允许您创建一个新的、定义的小部件。

<CustomButton@Button>:
    background_color: (1,0,0,1)

Then use the button wherever you want with the following syntax.然后使用以下语法在您想要的任何位置使用该按钮。 CustomButton:

  1. Use rules:使用规则:

At the start of the script, assign properties to a widget using the following syntax.在脚本开始时,使用以下语法为小部件分配属性。

<Button>:
    background_color:(1,0,0,1)

Any widget called after its creation will be created with those attributes.创建后调用的任何小部件都将使用这些属性创建。

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

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