python中删除按钮的实现,Python的Kivy的ListView:如何删除选定ListItemButton?

I'm trying to learn kivy by building a simple todo-list app like suggested by Dusty Phillips, author of the book "Creating apps in Kivy".

This is the code so far:

from kivy.app import App

from kivy.uix.boxlayout import BoxLayout

from kivy.properties import ObjectProperty

from kivy.uix.listview import ListItemButton

class TaskButton(ListItemButton):

pass

class TodoRoot(BoxLayout):

task_input = ObjectProperty()

task_list = ObjectProperty()

def add_task(self):

self.task_list.adapter.data.extend([self.task_input.text])

self.task_list._trigger_reset_populate()

def del_task(self):

pass

class TodoApp(App):

def build(self):

return TodoRoot()

if __name__ == '__main__':

TodoApp().run()

And this is the kv file:

#: import main todo

#: import ListAdapter kivy.adapters.listadapter.ListAdapter

#: import ListItemButton kivy.uix.listview.ListItemButton

TodoRoot:

:

orientation: "vertical"

task_input: task_input_view

task_list: tasks_list_view

BoxLayout:

size_hint_y: None

height: "40dp"

TextInput:

id: task_input_view

size_hint_x: 70

Button:

text: "Add"

size_hint_x: 15

on_press: root.add_task()

Button:

text: "Del"

size_hint_x: 15

on_press: root.del_task()

ListView:

id: tasks_list_view

adapter:

ListAdapter(data=[], cls=main.TaskButton)

This is what it looks like:

CTUib.png

I know the ListView API is still somewhat experimental and I'm complaining about the examples on using adapters / converters, google & SO search didn't help either. So what code is needed to make the Del-Button work and remove a selected ListItemButton?

解决方案

After a lot of reading ListView API docs & examples, I finally found out myself. What we need is the selection-Property of the listadapter-Class, then we can simply call the inherited remove method of the adapter.data-ListProperty.

So for anyone interesested this is the code:

def del_task(self, *args):

if self.task_list.adapter.selection:

selection = self.task_list.adapter.selection[0].text

self.task_list.adapter.data.remove(selection)

self.task_list._trigger_reset_populate()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值