首页 > 解决方案 > 在kivy的不同屏幕上动画图像

问题描述

我试图在切换轮播时自动为放置在另一个类中的图像设置动画。使用按钮它可以正常工作,但不会自动运行。我用“id”尝试了不同的东西,但我对此比较陌生,所以可能存在一个普遍的错误。通常屏幕管理器中有 2 个屏幕,第二个屏幕通向轮播。由于简单,我让第一个屏幕出来。此外,我计划在 Screen1 中播放一部电影,并希望在用户切换到 Screen2 时停止它。我认为主要问题是如何控制不同类中的功能。

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.carousel import Carousel
from kivy.uix.label import Label
from kivy.animation import Animation
from kivy.uix.image import Image

Builder.load_string('''

#:import FadeTransition kivy.uix.screenmanager.FadeTransition

<Screen1>:
    name: "screen1"
    Image:
        id: image1
        source: './img/somearrowup.png'
        pos: 205, 145
    Label:
        text: 'Screen down'
    BoxLayout:
        size_hint: .85,.15                  
        Button:
            text: 'Anim1'
            on_release: root.anim1()

<Screen2>:
    name: "screen2"
    Image:
        id: image2
        source: 'somearrowdown.png'
        pos: 205, 55
    Label:
        text: 'Screen Up'
    BoxLayout:
        size_hint: .85,.15
        Button:
            text: 'Anim2'
            on_release: root.anim2()

<Carou>:
    Screen:
        Carousel:
            id: carousel
            on_index: root.on_index(*args)
            direction: 'top'
            Screen1:
            Screen2:

''')

class Screen1(Screen):    
    def anim1(self):
        self.ids.image1.pos = 205, 155
        animation = Animation(pos=(205, 145),t='out_elastic')
        animation.start(self.ids.image1)

class Screen2(Screen):
    def anim2(self):
        self.ids.image2.pos = 205, 55
        animation = Animation(pos=(205, 45),t='out_elastic')
        animation.start(self.ids.image2)

class Carou(BoxLayout):    
    def on_index(self, instance, value):
        if instance.current_slide.name == 'screen2':
            print ("here an animation in Screen2")
            screen = Screen2()  #doesn't work
            screen.anim2()      #doesn't work
        else:
            print ("here an animation in Screen1")
            #...

class StartMenu(App):        
    def build(self):        
        sm = ScreenManager()        
        screen = Screen()        
        screen.add_widget(Carou())
        screen.name = 'carousel'
        sm.add_widget(screen)

        return sm

我会很感激你的帮助。

标签: pythonanimationkivy

解决方案


您的问题是,在您的on_index()方法中,您正在创建一个新方法Screen2并调用它的anim2()方法。您真正想要的是anim2()Screen2 您的Carousel. 为此,请替换:

screen = Screen2()

和:

screen = instance.current_slide

推荐阅读