【问题标题】:Kivy moving a widgetKivy 移动一个小部件
【发布时间】:2019-05-23 01:23:53
【问题描述】:

无法使用 Kivy 移动小部件

我想移动一个矩形并遵循 youtube 中使用的代码(亚历山大泰勒的 kivy 速成课程 11)。代码后矩形出现在屏幕上但不移动

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>

没有错误消息。但不能移动小部件

【问题讨论】:

    标签: python user-interface kivy


    【解决方案1】:

    您需要以某种方式引用矩形。您可以在 python 中制作它,并将 tha rectangle 定义为小部件的类属性。在下面的例子中,我只取画布的最后一个孩子,在这种情况下是矩形,并设置它的位置。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多