How to remove dynamically added items in Kivy

99封情书 提交于 2021-02-11 15:54:22

问题


I've asked in past questions how to add buttons dynamically.

I know how to add dynamically, but I don't know how to remove a button I've added.

I want to make sure that pressing RemoveButton removes the button that was pressed, as shown in the image below.

The code is as follows.

I don't know how to add a command to a dynamically added button.

#-*- coding: utf-8 -*-
from kivy.config import Config
from kivy.uix.button import Button

Config.set('graphics', 'width', 300)
Config.set('graphics', 'height', 300)
Config.set('input', 'mouse', 'mouse,multitouch_on_demand')  # eliminate annoying circle drawing on right click

from kivy.lang import Builder
Builder.load_string("""
<AddItemWidget>:
    BoxLayout:
        size: root.size
        orientation: 'vertical'

        RecycleView:
            size_hint: 1.0,1.0

            BoxLayout:
                id: box
                orientation: 'vertical'

                Button:
                    id: button1
                    text: "Button1"

                Button:
                    id: addButton
                    text: "Add Item"
                    on_press: root.buttonClicked()
""")

from kivy.app import App
from kivy.uix.widget import Widget

from kivy.properties import StringProperty

class RemovableButton(Button):
    def on_touch_down(self, touch):
        if touch.button == 'right':
            if self.collide_point(touch.x, touch.y):
                self.parent.remove_widget(self)
                return True
        return super(RemovableButton, self).on_touch_down(touch)


class AddItemWidget(Widget):
    text = StringProperty()

    def __init__(self, **kwargs):
        super(AddItemWidget, self).__init__(**kwargs)
        self.count = 1

    def buttonClicked(self):
        print("add item test")
        self.count += 1
        newButt = RemovableButton(text='Button'+ str(self.count))
        self.ids.box.add_widget(newButt, index=1)


class TestApp(App):
    def __init__(self, **kwargs):
        super(TestApp, self).__init__(**kwargs)

    def build(self):
        return AddItemWidget()

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

回答1:


You have to bind the removal action to the on_realease event of the button:

        newButt = RemovableButton(text='Button' + str(self.count))
        newButt.bind(on_release=self.ids.box.remove_widget)  # add this...
        self.ids.box.add_widget(newButt, index=1)


来源:https://stackoverflow.com/questions/61745788/how-to-remove-dynamically-added-items-in-kivy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!