首页 文章

Kivy中心小工具

提问于
浏览
1

我正在学习使用Kivy,所以我浏览了Pong教程并开始搞乱代码 . 所以,除了弹跳球之外我删除了所有东西,并决定按需生成多个球 . 我遇到的问题是,当应用程序已经运行时,我可以将球放在我想要的位置(例如,在触摸时添加球可以正常工作),但是当我在app build()中添加球时,它们不会得到放在右边 . 这是我的代码 . 接触球,正确地从中心开始 . 但是build()中添加的球从左下角开始 . 为什么?我想添加更多具有不同属性的移动小部件,但我似乎无法弄清楚如何将它们放在应用程序启动上 .

#:kivy 1.0.9
<World>:
    canvas:
        Ellipse:
            pos: self.center
            size: 10, 10

<Agent>:
    size: 50, 50
    canvas:
        Ellipse:
            pos: self.pos
            size: self.size
from random import randint

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ReferenceListProperty, ListProperty
from kivy.vector import Vector
from kivy.clock import Clock


class World(Widget):
    agents = ListProperty()

    def add(self):
        agent = Agent()
        agent.center = self.center
        agent.velocity = Vector(4, 0).rotate(randint(0, 360))
        self.agents.append(agent)
        self.add_widget(agent)

    def on_touch_down(self, touch):
        self.add()

    def update(self, dt):
        for agent in self.agents:
            agent.move()
            if agent.y < 0 or agent.top > self.height:
                agent.velocity_y *= -1
            if agent.x < 0 or agent.right > self.width:
                agent.velocity_x *= -1


class Agent(Widget):
    velocity_x = NumericProperty(0)
    velocity_y = NumericProperty(0)
    velocity = ReferenceListProperty(velocity_x, velocity_y)

    def move(self):
        self.pos = Vector(*self.velocity) + self.pos


class WorldApp(App):
    def build(self):
        world = World()
        # add one ball by default
        world.add()
        Clock.schedule_interval(world.update, 1.0/60.0)
        return world


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

1 回答

  • 2

    找到了答案 . 默认小部件大小为100,100 . 当我添加初始球时,World小部件不会呈现,因此具有默认大小 . 但是可以在Widget构造函数中传递窗口大小 . 所以改变世界实例化

    world = World(size=Window.size)
    

    解决了这个问题

相关问题