python - Kivy 从代码中选择 ListView 中的一个项目

标签 python listview kivy

我使用 ListAdapter 在 ListView 中显示数据。

如何从代码中选择 ListView 中的项目?

最佳答案

您可以使用 get_view() 方法从 ListAdapter 获取您的列表项。如果列表项是 ListItemButton,那么您可以使用 ButtonBehavior 混合的 trigger_action() 方法模拟按下(ButtonBehaviorButtonButton 的父级是 ListItemButton 的父级)。这也会触发 on_selection_change 事件,因此您可能需要一个变量来区分这与正常选择。一个例子:

from kivy.uix.listview import ListView, ListItemButton
from kivy.uix.boxlayout import BoxLayout
from kivy.adapters.dictadapter import ListAdapter
from kivy.uix.button import Button
from random import randint

class MainView(BoxLayout):
    def __init__(self, **kwargs):
        kwargs['cols'] = 2
        super(MainView, self).__init__(**kwargs)
        self.orientation = 'vertical'

        self.list_adapter = ListAdapter(data=["Item #{0}".format(i) for i in range(10)], cls=ListItemButton, sorted_keys=[])
        self.list_adapter.bind(on_selection_change=self.selection_change)
        list_view = ListView(adapter=self.list_adapter)
        self.add_widget(list_view)
        self.add_widget(Button(text="select random item", on_press=self.callback))

    def callback(self, instance):
        index = randint(0, 9)
        self.change_from_code = True
        if not self.list_adapter.get_view(index).is_selected:
            self.list_adapter.get_view(index).trigger_action(duration=0)
        self.change_from_code = False

    def selection_change(self, adapter, *args):
        if self.change_from_code:
            print "selection change from code"
        else:
            print "selection changed by click"

if __name__ == '__main__':
    from kivy.base import runTouchApp
    runTouchApp(MainView(width=800))

关于python - Kivy 从代码中选择 ListView 中的一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19459808/

相关文章:

java - 陷入 JavaFX ListView 困境

python - 如何在kivy python中使用滚动条

android - 绑定(bind)多个语句以在 kivy 中尝试表达式

python - 使用生成器逐行读取 json

java - listview.setAdapter(null) 似乎不起作用

python - Matplotlib 绘制数百个矩形轮廓

java - 我无法刷新 ListView

android - Python、Kivy 和 Android 游戏

python - 查找/删除目录中最旧的文件

php - 从 Python/AppEngine 迁移到 PHP 的最佳框架