azura azura - 3 months ago 62
Python Question

Need advice, remove widget for kivy

New in the world of programming for about months now.

need a help, regarding remove_widget.

please find my simple code for troubleshooting. I've been working on this for about 2 weeks and i cant find a work around to it.

basically this code add a button object and should also remove the obj.
but when i click delete button it doesn't remove the button that was added. Instead its like creating new button and removing it.

Thanks.

from kivy.uix.widget import Widget
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
from kivy.uix.button import Button

kv_string = Builder.load_string('''

<MScreen>:
FloatLayout:
Button:
pos: root.x,root.top-self.height
id: main_add
text: 'Add'
size_hint: .1,.05
on_release: root.add_item(1)
Button:
pos: root.x,root.top-main_add.height-self.height
id: main_del
text: 'Delete'
size_hint: .1,.05
on_release: root.rem_item()
''')
count = 0
class AddRem(Widget):
def addrem(self,add):
global count
self.wid = Widget()
self.list_btn = []

if add == 1:
count +=1

for self.index in range(count):
self.list_btn.append(Button(text=str(self.index), size_hint= (None,None), width=120, height=50, pos=(200,50+(self.index*10))))

self.add_widget(self.wid)

class MScreen(Screen,AddRem):

def add_item(self,add):
self.addrem(add)
for index in range(count):
self.wid.add_widget(self.list_btn[index])


def rem_item(self):
self.wid.remove_widget(self.list_btn.pop())

class myApp1(App):
def build(self):
return SManage

SManage = ScreenManager()
SManage.add_widget(MScreen())

if __name__ == "__main__":
myApp1().run()

Answer

A simple example of add remove buttons I can think of right now, could look like this.

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout


class MyBox(BoxLayout):

    def __init__(self,**kwargs):
        super(MyBox,self).__init__(**kwargs)
        self.orientation = "vertical"

        self.count = 0

        self.controlbuttons = BoxLayout(orientation="horizontal")

        self.controlbuttons.add_widget(Button(on_press=self.add_button,text="Add Button"))
        self.controlbuttons.add_widget(Button(on_press=self.remove_button,text="Remove Button"))

        self.buttons = BoxLayout(orientation="vertical")

        self.add_widget(self.controlbuttons)
        self.add_widget(self.buttons)

    def add_button(self,*args):
        self.count += 1
        self.buttons.add_widget(Button(text=str(self.count)))

    def remove_button(self,*args):
        if len(self.buttons.children):
            self.count -= 1
            self.buttons.remove_widget(self.buttons.children[0])


class MyApp(App):
    def build(self):
        return MyBox()


if __name__ == "__main__":
    MyApp().run()