Home > OS >  Line is not drawn in Kivy python
Line is not drawn in Kivy python

Time:01-29

Code:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Color
from kivy.graphics import Line


class Draw(Widget):
    def __init__(self, **kwargs):
        super(Draw, self).__init__(**kwargs)

        # Widget has a property called canvas
        with self.canvas:
            Color(0, 1, 0, .5, mode='rgba')
            Line(points=(350, 400, 500, 800, 650, 400, 300, 650, 700, 650, 350, 400), width=3)

            Color(0, 0, 1, .5, mode='rgba')
            Line(bezier=(200, 100, 250, 150, 300, 50, 350, 100), width=3)


class MyApp(App):
    def build(self):
        return Draw()


if __name__ == "__main__":
    MyApp().run()


The result:

Both the green line and the blue line should show up, but only the green line shows up The Green line shows a star The Blue line shows a wave

CodePudding user response:

self.pos

If you resize the application from your code, you should notice that sometimes the blue line is plotted. This is because you did not bind the position of the widget with the canvas drawing (Line, Rectangle, etc...)

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Color
from kivy.graphics import Line


class Draw(Widget):
    def __init__(self, **kwargs):
        super(Draw, self).__init__(**kwargs)
        self.update_canvas()

    def update_canvas(self, *args):
        # Widget has a property called canvas
        with self.canvas:
            # add self.pos to the line position
            Color(0, 1, 0, .5, mode='rgba')
            Line(pos=self.pos, points=(350, 400, 500, 800, 650, 400, 300, 650, 700, 650, 350, 400), width=3)

            Color(0, 0, 1, .5, mode='rgba')
            Line(pos=self.pos, bezier=(200, 100, 250, 150, 300, 50, 350, 100), width=3)


class MyApp(App):
    def build(self):
        return Draw()


if __name__ == "__main__":
    MyApp().run()

However, I noticed that sometimes the blue line is not visible depending on the OpenGL Context initialization.

  • Related