KIVY:用时钟动画标签

时间:2018-02-27 14:39:29

标签: python kivy

逗人,

我正在尝试在Kivy中做一个非常简单的程序,它将在屏幕上随机移动一个Label(就像旧的屏幕保护程序一样)。

想使用时钟和随机

我做错了什么?

THKS

代码

from kivy.base import runTouchApp
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.clock import Clock
from kivy.properties import ListProperty
from kivy.core.window import Window
from random import random

Builder.load_string('''
<TransLabel>:
    Label :
        text: "test"
        pos: self.pos
        size: self.size
''')
class TransLabel(Label):
    velocity = ListProperty([10,15])

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

    def update(self,*args):
        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

runTouchApp(TransLabel())

1 个答案:

答案 0 :(得分:0)

包含文本的标签不应具有根的大小,因为在执行update()方法时,文本将会振荡,因为评估if的句子将始终为真。

您还必须比较文本相对于窗口的位置,而不是根与窗口的位置,因为它们具有相同的大小。

from kivy.base import runTouchApp
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.clock import Clock
from kivy.properties import ListProperty, NumericProperty
from kivy.core.window import Window
from random import randint

Builder.load_string('''
<TransLabel>:
    Label :
        id: label
        text: "test"
''')

class TransLabel(Label):
    velocity = ListProperty([10,15])

    def __init__(self, **kwargs):
        super(TransLabel,self).__init__(**kwargs)
        Clock.schedule_interval(self.update, 1./60)
        self.x = randint(0, self.width)
        self.y = randint(0, self.height)

    def update(self,*args):
        self.x += self.velocity[0]
        self.y += self.velocity[1]

        label = self.ids.label

        if self.x <0 or (self.x + label.width) > Window.width:
            self.velocity[0] *= -1

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

        label.pos = [self.x, self.y]

runTouchApp(TransLabel())