Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
756 views
in Technique[技术] by (71.8m points)

python - How can I make a lot of buttons at dynamic in kv language?

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)

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)

How can I do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

Example:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...