Search code examples
pythonlabelkivyfadeout

Having a label fade out in kivy


So I want to display a label if someone tries to click play and there is no save file made yet. Then I want it to fade out. The while loop works, reducing the value of alpha to 0. And it displays the label as long as I don't have the self.remove_widget(no_save) added in but then it just stays as a solid label. Any help would be appreciated. Or is there an easier way to do this?

class StartMenu(Screen):

    def check_save(self):
        global save_state
        if save_state == None:
            color = (0,1,0,1)
            while color[3] > 0:
                no_save = Label(text='No save file found. Please press New Game', color=color)
                self.add_widget(no_save)
                color = color [:3] + (color[3] - (.1),)
                time.sleep(.1)
                self.remove_widget(no_save)

Solution

  • Rather than doing the fade out yourself, why not use the built in Animation functionality? Try something like this. I would also suggest moving save_state from the global realm to your class, and instead of creating and destroying the label every run, I would create at initialization and simply hide or show it as it becomes necessary.

    class StartMenu(Screen):
    
      def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.save_state = None
        no_save = Label('No save file found. Please press new game.', hidden=True)
        self.add_widget(no_save)
    
    
      def check_save(self):
        if not self.save_state:
           self.no_save.hidden = False
           def hide_label(w): w.hidden = True
           Animation(opacity=0, duration=1, on_complete=hide_label).start(self.no_save)
    

    Quick shoutout to zeeMonkeys for pointing out the Animation solution in the comments before I did.