問題描述
我正在嘗試通過構建一個簡單的待辦事項列表應用程序來學習 kivy,就像在 Kivy 中創建應用程序"一書的作者 Dusty Phillips 所建議的那樣.
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".
這是目前為止的代碼:
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()
這是kv文件:
#: import main todo
#: import ListAdapter kivy.adapters.listadapter.ListAdapter
#: import ListItemButton kivy.uix.listview.ListItemButton
TodoRoot:
<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)
這是它的樣子:
我知道 ListView API 仍處于試驗階段,我抱怨有關使用適配器/轉換器、google &所以搜索也沒有幫助.那么需要什么代碼才能使 Del-Button 工作并刪除選定的 ListItemButton?
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?
推薦答案
大量閱讀 ListView API docs &例子,我終于找到了自己.我們需要的是listadapter-Class的selection-Property,那么我們可以簡單的調用adapter.data-ListProperty繼承的remove方法.
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()
這篇關于Python Kivy ListView:如何刪除選定的 ListItemButton?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!