Sarala
Sarala

Reputation: 21

Kivy moving a widget

Unable to move a widget using Kivy

I want to move a rectangle and have followed the code used in youtube (kivy crash course 11 by Alexander Taylor ). After the code the rectangle appears on screen but does not move

python code

class CRect:
    velocity = ListProperty([20, 10])

    def __init__(self, **kwargs):
        super(CRect, self).__init__(**kwargs)
        Clock.schedule_interval(self.update, 1/60)

    def update(self):
        self.x += self.velocity[0]
        self.y += self.velocity[1]

        if self.x < 0 or (self.x+self.width) > Window.width:
            self.velocity[0] *= -1

        if self.y < 0 or (self.y+self.height) > Window.height:
            self.velocity[1] *= -1


if __name__ == '__main__':
    RRApp().run()

kv code

<DemoCreator>:
    CRect:

        canvas:
            Color:
                rgba: 1,0,0,1
            Rectangle:
                pos: 100,0
                size: 40,40

<CRect@Widget>

No error messages. But ca not move the widget

Upvotes: 0

Views: 699

Answers (1)

el3ien
el3ien

Reputation: 5405

You need to reference the rectangle somehow. You could make that in python, and define tha rectangle as a class attribute for the widget. In the following example, I just take the last of the canvas' children which in this case is the rectangle, and set its position.

from kivy.uix.widget import Widget
from kivy.app import App
from kivy.lang import Builder
from kivy.properties import ListProperty
from kivy.clock import Clock
from kivy.core.window import Window

KV = """

CRect:
    canvas:
        Color:
            rgba: 1,0,0,1
        Rectangle:
            pos: 100,0
            size: 40,40


"""

class CRect(Widget):
    velocity = ListProperty([20, 10])
    rect_x, rect_y = 0, 0

    def __init__(self, **kwargs):
        super(CRect, self).__init__(**kwargs)
        Clock.schedule_interval(self.update, 1/60)

    def update(self, dt):
        rect = self.canvas.children[-1]
        self.rect_x += self.velocity[0]
        self.rect_y += self.velocity[1]

        rect.pos = self.rect_x, self.rect_y

        if self.rect_x < 0 or (self.rect_x+rect.size[0]) > Window.width:
            self.velocity[0] *= -1

        if self.rect_y < 0 or (self.rect_y+rect.size[1]) > Window.height:
            self.velocity[1] *= -1


class MyApp(App):
    def build(self):
        return Builder.load_string(KV)

MyApp().run()

Upvotes: 2

Related Questions