如何在 kv 语言中动态制作很多按钮?

2022-01-15 00:00:00 python kivy kivy-language loops dynamic

问题描述

我想用 kv 语言制作很多动态按钮.但是现在我不能......我现在将在此下显示源代码.

I want to make a lot of Buttons at dynamic in kv language. But now I cannot...... I will show now source under this.

BoxLayout:
    orientation: 'vertical'
    pos: root.pos
    size: root.size

    GridLayout:
        rows: 2
        spacing: 5
        padding: 5

        Button:
            text: "X0"
            on_press: root.X(0)
        Button:
            text: "X1"
            on_press: root.X(1)

我想在code下做like

I want to make like under code

BoxLayout:
    orientation: 'vertical'
    pos: root.pos
    size: root.size

    GridLayout:
        rows: 2
        spacing:5
        padding:5

        for i
            Button:
                text: "X#{i}"
                on_press: root.X(i)

我该怎么办?


解决方案

这样的循环在 kv 语言中是不可能的,除了做一些肮脏的 hack.

Such loops aren't possible in kv language, other than doing some dirty hacks.

要动态创建一组按钮,请使用 ListView 或将它们添加到 py 文件中的循环中.

To create a set of buttons dynamically, either use ListView or add them in a loop inside a py file.

例子:

from functools import partial

class MyGrid(GridLayout):
    def __init__(self, **kwargs):
        super(MyGrid, self).__init__(**kwargs)
        self.add_buttons()

    def add_buttons(self):
        for i in xrange(5):
            button = Button(
                text='X' + str(i),
                on_press=partial(self.X, number=i)
            )
            self.add_widget(button)

    def X(self, caller, number):
        print  caller, number

相关文章