Kivy- 使用选择 Recycleview 分配变量

Kivy- Assign variables with on selection Recycleview

我有一个问题可能 python-无知而不是 kivy 问题。

我不会在 python 中编写 kivy,所以我有 KV 文件和 py 文件。

我已经使用 kivy 文档中的 SelectableLabel 修改了 Recycleview。但是,与所有其他小部件不同,这个小部件的工作方式不同。

这是main.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from kivy.config import Config   
try:
    import kivy
except ImportError:
    raise ImportError("this backend requires Kivy to be installed.")


from kivy.uix.recycleview import RecycleView
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.label import Label
from kivy.properties import BooleanProperty
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout

class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior,
                                 RecycleBoxLayout):
    ''' Adds selection and focus behaviour to the view. '''


class SelectableLabel(RecycleDataViewBehavior, Label):
    ''' Add selection support to the Label '''
    index = None
    selected = BooleanProperty(False)
    selectable = BooleanProperty(True)

    def refresh_view_attrs(self, rv, index, data):
        ''' Catch and handle the view changes '''
        self.index = index
        return super(SelectableLabel, self).refresh_view_attrs(
            rv, index, data)

    def on_touch_down(self, touch):
        ''' Add selection on touch down '''
        if super(SelectableLabel, self).on_touch_down(touch):
            return True
        if self.collide_point(*touch.pos) and self.selectable:
            return self.parent.select_with_touch(self.index, touch)

    def apply_selection(self, rv, index, is_selected):
        ''' Respond to the selection of items in the view. '''
        self.selected = is_selected
        self.change_this_variable = 'Here'
        """I wish to change this variable that belongs to MainWindow instance
        """
        if is_selected:
            print("selection changed to {0}".format(rv.data[index]))
        else:
            print("selection removed for {0}".format(rv.data[index]))



class MainWindow(BoxLayout):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.change_this_variable = '' # Variable I want to change from 
        #                                select_event

        #My whole app logic is here
        #
        #

class guitApp(App):
    pass

if __name__ == '__main__':
    guitApp().run()

这里是guit.kv

MainWindow:                                
    BoxLayout:

        RecycleView:
            id: rv
            data:[{'text': str(x)} for x in range(10)] # #
            viewclass: 'SelectableLabel'
            SelectableRecycleBoxLayout:
                id: slr
                default_size: None, dp(56)
                default_size_hint: 1, None
                size_hint_y: None
                height: self.minimum_height
                orientation: 'vertical'
                multiselect: False
                touch_multiselect: True


<SelectableLabel>:
    # Draw a background to indicate selection
    canvas.before:
        Color:
            rgba: (1, 0.866, .0, 1) if self.selected else (0, 0.419, 1,1)
        Rectangle:
            pos: self.pos
            size: self.size

我的问题是,我通常用 kivy 语言创建小部件,通过 id 引用或 on_event: root.function() 在 kivy 中给它 id 并在 main.py 中执行逻辑郎。但是通过文档中的这个 SelecteableLabel 和 RecycleView,我得到了名为 apply_selection 的 on_event 函数,但它在 Gui 对象(MainWindow,所有逻辑发生的地方)之外,所以我无法访问它。我不想用 Globals 解决这个问题。 所以我的问题是,如何在我的 Gui 对象中获取 apply_selection,以便我可以为 MainWindow 的变量赋值(如 self.change_this_variable)?

不需要在 MainWindow() 中获取 apply_selection() 方法。解决方案是使用App.get_running_app().root获取MainWindow()的一个实例,你可以参考它的属性和方法如下:

片段

def apply_selection(self, rv, index, is_selected):
    ''' Respond to the selection of items in the view. '''
    self.selected = is_selected

    App.get_running_app().root.change_this_variable = 'Here'

    """I wish to change this variable that belongs to MainWindow instance
    """

    if is_selected:
        print("selection changed to {0}".format(rv.data[index]))
    else:
        print("selection removed for {0}".format(rv.data[index]))