如何在Kivy中删除动态添加的项目 [英] How to remove dynamically added items in Kivy
本文介绍了如何在Kivy中删除动态添加的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在过去的问题中问过如何动态添加按钮.
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.
我要确保按下RemoveButton会删除按下的按钮,如下图所示.
I want to make sure that pressing RemoveButton removes the button that was pressed, as shown in the image below.
代码如下.
我不知道如何向动态添加的按钮添加命令.
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()
推荐答案
您必须将删除操作绑定到按钮的on_realease
事件:
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)
这篇关于如何在Kivy中删除动态添加的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文