Search code examples
buttonkivy

How to add a Label and delete it in a second


I want to add new text on the screen by clicking on the button and after a second so that it disappears, it's just as interesting how to make its smooth appearance and smooth disappearance.

I was created a text addition on the screen by clicking, but I do not know how to make it disappear after a while

my cod is here:

test1.py:

from kivy.app import App
import random
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.uix.screenmanager import Screen, ScreenManager

class ScreenOne(Screen):
    def on_press(self):
        x = random.randint(-250, 300)
        y = random.randint(-250, 300)

        Bl = self.ids.Fl
        label = Label(text="+", font_size=30, pos=(x, y))
        Bl.add_widget(label)

class manager(ScreenManager):
    pass



kv = Builder.load_file("test1.kv")
class test(App):
   def build(self):
       return kv

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

and test1.kv:


manager:
    ScreenOne:

<ScreenOne>
    name: "ScreenOne"
    FloatLayout:
        id: Fl
        size: root.width, root.height
        Button:
            size_hint: .2, .2
            pos: self.width * 2, self. height * 2
            text: "press ME"
            on_release: root.on_press()

Solution

  • just include the Clock.schedule_once function from kivy. here you go:

    from kivy.app import App
    import random
    from kivy.lang import Builder
    from kivy.uix.label import Label
    from kivy.uix.screenmanager import Screen, ScreenManager
    
    from functools import partial
    from kivy.clock import Clock
    
    
    class ScreenOne(Screen):
        def on_press(self):
            self.my_float_layout = self.ids.my_float_layout
    
            self.label = Label(text="+", font_size=30, pos=(random.randint(-250, 300), random.randint(-250, 300)))
            self.my_float_layout.add_widget(self.label)
    
            Clock.schedule_once(partial(self.delete_label, self.label), 1) #calls the delete_label function 1 second later
    
        def delete_label(self, label, dt):
           if label in self.my_float_layout.children:
                self.my_float_layout.remove_widget(label)
    
    class Manager(ScreenManager):
        pass
    
    class TestApp(App):
       def build(self):
           return Builder.load_file("test1.kv")
    
    if __name__ == '__main__':
       TestApp().run()
    

    and your test1.kv file:

    Manager:
        ScreenOne:
    
    <ScreenOne>
        name: "ScreenOne"
        FloatLayout:
            id: my_float_layout
            size: root.width, root.height
            Button:
                size_hint: .2, .2
                pos: self.width * 2, self. height * 2
                text: "press ME"
                on_release: root.on_press()