Skip to content
Advertisement

How does the ‘with’ statement work in kivy?

I have been playing with kivy, and I saw this:

    with self.canvas:
        Color(1, 1, 0)  # <--- no assignment
        d = 30.
        Ellipse(pos=(touch.x - d / 2, touch.y - d / 2), size=(d, d))  # <--- no assignment

I don’t quite understand how it works. I was expecting to see something like:

    with self.canvas as c:
        c.color = Color(1, 1, 0)
        c.shape = Ellipse()

What am I missing?

Advertisement

Answer

with some_canvas sets an internal Kivy variable to that canvas. When canvas instructions are created they check if that variable is set to a canvas, and if so they automatically add themselves to it.

If you want to trace through how this works you can find the context entry function here, and the code that automatically adds instructions to a canvas when instantiated here.

I don’t quite understand how it works. I was expecting to see something like:

with self.canvas as c:
    c.color = Color(1, 1, 0)
    c.shape = Ellipse()

In this case the with context wouldn’t really be doing anything. If you want to explicitly manipulate the canvas you can do it directly without a context manager, e.g. self.canvas.add(Color(1, 1, 0)).

That said, the way you’ve written this may indicate a misunderstanding: a canvas doesn’t have a specific colour as you’ve indicated with c.color, rather it’s a list of instructions to apply in order. There could be many Color instructions, with different numbers of other instructions (e.g. representing different shapes) in between.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement