1

I have some .kv that I'm frequently changing, which has multiple identical sections (but with different ids). Eg:

GridLayout:
    cols: 1

    Button:
        id: button1
        text: 'Button 1'
        on_press: app.buttonpressed(1)

    Button:
        id: button2
        text: 'Button 2'
        on_press: app.buttonpressed(2)

    Button:
        id: button3
        text: 'Button 3'
        on_press: app.buttonpressed(3)

...and so on. Is there a way of defining the button once and reusing it? Obviously I could do this in python, ie without using .kv but I want to keep everything in .kv

user4893295
  • 533
  • 6
  • 25
  • 1
    Possible duplicate of [How can I make a lot of buttons at dynamic in kv language?](http://stackoverflow.com/questions/35856891/how-can-i-make-a-lot-of-buttons-at-dynamic-in-kv-language) – zeeMonkeez Jun 02 '16 at 19:28
  • Not a real kv solution as why it isn't possible was already mentioned in the answer, but make a `f(widget, parent, count)` that uses `parent.add_widget(widget)` in python's for loop and you are good to go ^^ – Peter Badida Jun 03 '16 at 05:24

1 Answers1

0

You can use kivy dynamic classes (and templates for older versions).

Here's an example from the documentation (https://kivy.org/docs/guide/lang.html#dynamic-classes).

<CustomButton@Button>:
    text_size: self.size
    font_size: '25sp'
    markup: True

<MyWidget>:
    CustomButton:
        text: "Hello world, watch this text wrap inside the button"
    CustomButton:
        text: "Even absolute is relative to itself"
    CustomButton:
        text: "repeating the same thing over and over in a comp = fail"
    CustomButton:
Alexis Clarembeau
  • 2,776
  • 14
  • 27
  • I'm actually already using classes, but it's a long and complex bit of kv, with many levels of widgets within other widgets, so whilst the classes are taking some of the weight, it's still quite a faff to change all the structure for each tree. – user4893295 Jun 02 '16 at 19:30
  • So, I'm afraid you can't do that only with kv language (without python) as kv is a "description language" and not something as dynamic as a real language with loops, functions, ... – Alexis Clarembeau Jun 02 '16 at 19:42
  • 1
    Fair enough. I'll probably create a template and then use python code to generate the .kv then, but thought I'd better check if there was a way of doing it natively.... – user4893295 Jun 02 '16 at 19:50
  • It was a good approach ;) So, I suggest to mark that question as closed – Alexis Clarembeau Jun 02 '16 at 20:16