Kivy非GUI事件

时间:2016-09-12 16:49:50

标签: python events event-handling kivy kivy-language

我正在尝试在首次加载应用时启动动画。 I.E.加载屏幕关闭后立即。我已经厌倦了#34; on_enter"事件但它似乎没有用,任何帮助都会非常感激。

from kivy.base import runTouchApp
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.animation import Animation
from kivy.properties import ListProperty
from kivy.core.window import Window
from random import random
from kivy.graphics import Color, Rectangle

Builder.load_string('''
<Root>:
AnimRect:
    pos: 500, 300
<AnimRect>:
on_enter: self.start_animation
canvas:
    Color:
        rgba: 0, 1, 0, 1
    Rectangle:
        pos: self.pos
        size: self.size
''')

class Root(Widget):
pass

class AnimRect(Widget):
    def anim_to_random_pos(self):
        Animation.cancel_all(self)
        random_x = random() * (Window.width - self.width)
        random_y = random() * (Window.height - self.height)

        anim = Animation(x=random_x, y=random_y,
                     duration=4,
                     t='out_elastic')
        anim.start(self)

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            self.anim_to_random_pos()

    def start_animation(self, touch):
        if self.collide_point(*touch.pos):
             self.anim_to_random_pos()

runTouchApp(Root())

print screen of error

2 个答案:

答案 0 :(得分:0)

on_enter方法在Screen中定义,而不在Widget中定义。您应该将该矩形放在屏幕上(此处Root小部件应该是一个屏幕),一旦屏幕的on_enter事件触发,就启动矩形动画。

另外,你正在调用它;函数调用应包含括号,即on_enter: self.start_animation()

答案 1 :(得分:0)

它看起来像你想要的东西吗?

我刚刚删除了你的kv中的“on_enter”行,并更正了你的缩进。

from kivy.base import runTouchApp
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.animation import Animation
from kivy.properties import ListProperty
from kivy.core.window import Window
from random import random
from kivy.graphics import Color, Rectangle

Builder.load_string('''
<Root>:
    AnimRect:
        pos: 500, 300
<AnimRect>:
    canvas:
        Color:
            rgba: 0, 1, 0, 1
        Rectangle:
            pos: self.pos
            size: self.size
''')

class Root(Widget):
    pass

class AnimRect(Widget):
    def anim_to_random_pos(self):
        Animation.cancel_all(self)
        random_x = random() * (Window.width - self.width)
        random_y = random() * (Window.height - self.height)

        anim = Animation(x=random_x, y=random_y,
                     duration=4,
                     t='out_elastic')
        anim.start(self)

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            self.anim_to_random_pos()

    def start_animation(self, touch):
        if self.collide_point(*touch.pos):
             self.anim_to_random_pos()

runTouchApp(Root())