Search code examples
pythonkivykivy-language

cannot remove widget in Kivy


i cannot remove widget using the screen with kivy python, i dont know why it just does not do anything the code was suppose to remove textinput with id:name on the first screen but it just does not do anything and no error message. here is all of the code it is tested on python 3.7.4, kivy 1.11.1 on window.

module_media_player.py

import kivy

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.lang import Builder
from kivy.core.audio import SoundLoader
from kivy.uix.videoplayer import VideoPlayer
from kivy.uix.screenmanager import ScreenManager,Screen



class Player(Screen):
    def press(self):
        self.ids.name.text = 'nice'
    def remove(self):
        self.remove_widget(self.ids.name)
class MediaPlayer(Screen):
    pass
class WindowManager(ScreenManager):
    pass

kv = Builder.load_file('my.kv')
class GoodApp(App):
    def build(self):
        return kv


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

my.kv

WindowManager:
    Player:
    MediaPlayer:

<Player>:
    name:"player"

    BoxLayout:
        orientation:"vertical"
        size:root.width,root.height
        cols:2

        TextInput:
            id:name
            multiline:False
            text:"first"
            font_size:12
            size_hint_y:0.3
        Button:
            text:"click me"
            on_press:root.remove()
        Button:
            text:"next window"
            font_size:14
            size_hint_y:0.7
            on_release:
                app.root.current = "mediaplayer"
                root.manager.transition.direction = "left"

<MediaPlayer>:
    name:"mediaplayer"
    BoxLayout:
        orientation:"vertical"
        size:root.width,root.height

        Label:
            text:"second"
            font_size:12

        Button:
            text:"previous window"
            font_size:14
            on_release:
                app.root.current = "player"
                root.manager.transition.direction = "right"

Solution

  • Your code:

    def remove(self):
        self.remove_widget(self.ids.name)
    

    is trying to remove the TextInput from the Player Screen, but that Textinput is not a child of Player. It is actually a child of the BoxLayout. You can fix this by modifying your remove() method:

    def remove(self):
        textinput = self.ids.name
        textinput.parent.remove_widget(textinput)  # remove widget from its parent