Kivy移动小部件 [英] Kivy moving a widget

查看:92
本文介绍了Kivy移动小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法使用Kivy移动小部件

Unable to move a widget using Kivy

我想移动一个矩形并遵循youtube中使用的代码(Alexander Taylor的kivy速成课程11).输入代码后,矩形会显示在屏幕上,但不会移动

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代码

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代码

<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

推荐答案

您需要以某种方式引用矩形.您可以在python中进行创建,然后将tha矩形定义为小部件的类属性.在下面的示例中,我只取了画布的最后一个孩子(在本例中为矩形),然后设置其位置.

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()

这篇关于Kivy移动小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆