Kivy小部件矩形不移动

时间:2019-11-20 03:58:18

标签: python kivy

嗨,当我运行我的代码时,它应该显示出上下移动的矩形形状。但是,我只能在静态模式下获得矩形形状(不能移动)。但是,根据小部件类下的功能,它应该可以工作。任何帮助将不胜感激!

countdown.py文件

from kivy.app import App
from kivy.lang import Builder
from kivy.properties import ListProperty
from kivy.uix.widget import Widget
from kivy.graphics import *
from kivy.clock import Clock
from kivy.uix.screenmanager import Screen, ScreenManager

class WindowManager(ScreenManager):
    pass

class GameWindow(Screen):
    def __init__(self, **kwargs):
        super(GameWindow, self).__init__(**kwargs)
        self.add_widget(Root())
        self.add_widget(Rect())


class Root(Widget):
    pass

class Rect(Widget):
    velocity = ListProperty([10, 2])

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

    def update(self, *args):

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


kys = Builder.load_file("countdown.kv")

class MyMainApp(App):
    def build(self):
        return kys

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

countdown.kv文件

WindowManager:
    GameWindow:

<GameWindow>:
    canvas:
        Color:
            rgba: 1, 0, 0, 1
        Rectangle:
            pos: self.pos
            size: (42,15)


    Rect:
        pos: 85, 100

1 个答案:

答案 0 :(得分:1)

小部件具有以下一些特征:

  • 如果将您放置为另一个小部件(屏幕,微调框等)的子代,则它将占用尽可能多的空间,因为size_hint为(1,1),在您的情况下,它将占据整个空间屏幕上的。

  • 由于没有背景色或其他视觉元素,因此无法区分。

基于上述内容,即使移动了作为小部件的“ Rect”,也无法区分,因此我们必须使用画布进行绘画(我想这是您在GameWindow中使用画布时尝试的方法),除了设置容器独立的大小外,还应将size_hint设置为(无,无)。

考虑到上述情况,解决方案是:

from kivy.app import App
from kivy.lang import Builder
from kivy.properties import ListProperty
from kivy.uix.widget import Widget
from kivy.clock import Clock
from kivy.uix.screenmanager import Screen, ScreenManager


class WindowManager(ScreenManager):
    pass


class GameWindow(Screen):
    pass


class Rect(Widget):
    velocity = ListProperty([10, 2])

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

    def update(self, *args):
        self.y += self.velocity[1]
        if self.y < 0 or (self.y + self.height) > 250:
            self.velocity[1] *= -1


kys = Builder.load_file("countdown.kv")


class MyMainApp(App):
    def build(self):
        return kys


if __name__ == "__main__":
    MyMainApp().run()
WindowManager:
    GameWindow:

<GameWindow>:
    Rect:

<Rect>:
    size_hint : None, None
    size : 42, 15
    canvas:
        Color:
            rgba: 1, 0, 0, 1
        Rectangle:
            pos: self.pos
            size: self.size