У меня вопрос о динамическом просмотре списка в python с kivy. Итак, список работает, но знаю, что я хочу получить текст из выбранного элемента списка, чтобы отправить его в файл python. Но я не могу найти никакого решения, которое мне подходит. Я думаю, что один из способов сделать это - "on_selection_change", но я не могу выполнить этот запуск. Итак, вот мой код
BoxLayout:
pos: 130,10
size: 500,400
ListView:
adapter:
ListAdapter(data=root.my_data,
args_converter=lambda row_index, an_obj: {'text': an_obj,'size_hint_y': 28,'height': 40, 'font_size': 20},
selection_mode='single',
allow_empty_selection=True,
cls=ListItemButton)
<ListItemButton>:
#on_selection_change=self.on_selection_change
on_release: app.getname()
и мой файл Python
class PCScreen(GridLayout,Screen):
filename = open("/home/pi/Documents/ppcont/config/name.txt")
my_data = ListProperty(filename)
def getname(self):
pass






Я действительно думаю, что вам следует сбросить ListView, он устарел (из документации):
ListAdapter:
Module: kivy.adapters.listadapter Added in 1.5
Deprecated since version 1.10.0: The feature has been deprecated.
вам действительно стоит использовать https://kivy.org/docs/api-kivy.uix.recycleview.html
Что касается ListView, используйте ModalView для управления выбором и вызовите метод getname (). Пожалуйста, обратитесь к двум примерам (ListView и RecycleView) для получения подробной информации.
Посмотреть список устарел с версии 1.10.0, используйте вместо него RecycleView.
from kivy.app import App
from kivy.uix.modalview import ModalView
from kivy.properties import ObjectProperty
class MyListView(ModalView):
list_view = ObjectProperty(None)
def __init__(self, **kwargs):
super(MyListView, self).__init__(**kwargs)
self.list_view.adapter.bind(on_selection_change=self.callback_function)
def callback_function(self, instance):
print(instance)
App.get_running_app().getname()
class MainListViewApp(App):
title = "ListView ListItemButton Demo"
def build(self):
return MyListView()
def getname(self):
print("App.getname() - Called")
if __name__ == '__main__':
MainListViewApp().run()
#:kivy 1.10.0
#:import lv kivy.uix.listview
#:import la kivy.adapters.listadapter
<MyListView>:
list_view: list_view
ListView:
id: list_view
adapter:
la.ListAdapter(
data=["Item #{0}".format(i) for i in range(100)],
selection_mode='single',
allow_empty_selection=True,
cls=lv.ListItemButton)
from kivy.app import App
from kivy.uix.recycleview import RecycleView
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.button import Button
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.properties import ObjectProperty
class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior, RecycleBoxLayout):
""" Adds selection and focus behaviour to the view. """
pass
class SelectableButton(RecycleDataViewBehavior, Button):
""" Add selection support to the Label """
index = None
def refresh_view_attrs(self, rv, index, data):
""" Catch and handle the view changes """
self.index = index
return super(SelectableButton, self).refresh_view_attrs(rv, index, data)
def on_release(self):
print("Pressed & released on", self.text)
App.get_running_app().getname()
class RV(RecycleView):
rv_layout = ObjectProperty(None)
def __init__(self, **kwargs):
super(RV, self).__init__(**kwargs)
self.data = [{'text': "Button " + str(x), 'id': str(x)} for x in range(100)]
class MainRecycleViewApp(App):
title = "RecycleView Button Demo"
def build(self):
return RV()
def getname(self):
print("RecycleView: App.getname() - Called")
if __name__ == "__main__":
MainRecycleViewApp().run()
#:kivy 1.10.0
<SelectableButton>:
# Draw a background to indicate selection
canvas.before:
Color:
rgba: (0.0, 0.9, 0.1, 0.3)
Rectangle:
pos: self.pos
size: self.size
<RV>:
rv_layout: layout
viewclass: 'SelectableButton'
SelectableRecycleBoxLayout:
id: layout
default_size: None, dp(26)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: "vertical"
предоставить минимальный воспроизводимый пример