如何在 kv 语言中动态制作很多按钮? [英] How can I make a lot of buttons at dynamic in kv language?

查看:31
本文介绍了如何在 kv 语言中动态制作很多按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 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

这篇关于如何在 kv 语言中动态制作很多按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆