Search code examples
python-3.xcanvaskivyline

How can we create several lines using a loop in a kv file? (Python3, kivy)


I'm just learning to code and I'm discovering kivy. I want to draw a grid using kivy language. The syntaxe of drawing a line is:

<Frontend>:
    canvas:
        Line:
            points: x_1, x_2, y_1, y_2

So I've decided to proceed the same way as if I was using Tkinter. As I've found, we can iterate widgets with kivy language. At least, it works with Labels.

#:import Label kivy.uix.label.Label
<Frontend>:
    on_parent:
        for i in range(3): self.add_widget(Label(text = 'Hello world'))

Meanwhile when I've tried to do the same thing with lines, it raised different errors, that seem to be logical, as we find Lines in kivy.graphics and other widgets in kivy.uix.

Nevertheless I've tried that (last try):

#:import ins kivy.graphics.instructions
#:import v kivy.graphics.vertex_instructions

<Frontend>:
    on_parent:
        for i in range(3): ins.Canvas.add(v.Line(points=(x_1, x_1, x_2, x_2)))

I've also tried "draw", but the two raised the same error: "descriptor 'add' for 'kivy.graphics.instructions.Canvas' objects doesn't apply to a 'kivy.graphics.vertex_instructions.Line' object".

So maybe it's impossible to create a grid thit way?


Solution

  • You can do something like this:

    #:import Line kivy.graphics.Line
    <Frontend>:
        pts: [100, 100, 500, 100,   100, 200, 500, 200,    100, 300, 500, 300]
        canvas:
            Color:
                rgba: 1,1,1,1
        on_parent:
            for i in range(0, len(root.pts), 4): self.canvas.add(Line(points=root.pts[i:i+4]))