Обновите список просмотра корзины после выбора в Kivy - PullRequest
0 голосов
/ 16 марта 2020

Моя цель похожа на

Я выбираю опцию из списка просмотра корзины из кнопки 1, после выбора опции, затем я выбираю из кнопки 2, теперь на дисплее не должно отображаться выбранное значение в кнопка 1 (ранее выбранная опция должна быть удалена из режима повторного просмотра 2). Более того, текст кнопки должен быть обновлен до текста выбранного значения.

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager,Screen,SlideTransition,FadeTransition  
from kivy.uix.checkbox import CheckBox
from kivy.properties import ObjectProperty, NumericProperty, BooleanProperty,ListProperty,StringProperty
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.base import runTouchApp
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.recycleview import RecycleView
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.recycleview.views import RecycleDataViewBehavior


alph = ['a','b','c','d','e','f','g','h','i']
val1_chsd = None
val2_chsd = None


class Screen3(Screen):
        #pass
        labeltext = StringProperty('My selection')

        def buttontype(self,types):
                global buttonval
                print("type called :",types)
                if types is "button1":
                        buttonval = "selection1"
                        print ('value set 1',buttonval)
                elif types is "button2":
                        buttonval = "selection2"
                        print ('value set 2',buttonval)

        def setvalueselected(self,sel_value):
                print("Selected value is",sel_value)
                global val1_chsd
                global val2_chsd              
                if buttonval is "selection1":
                        val1_chsd = sel_value
                        val1_name = sel_value
                        print("choosed no. 1",val1_name)

                if  buttonval is "selection2":
                        val2_chsd = sel_value
                        val2_name = sel_value
                        print("choosed no. 2",val2_name)

        def printselected(self):
                print("abcdef",val1_chsd,val2_chsd)
                if val1_chsd != None and val2_chsd != None:
                        selected = val1_chsd + '\n' + val2_chsd
                        print ("choosed : ",selected)
                        self.labeltext = selected
                else:
                        print ("Choose all values")


class Screen4(Screen):
    list = ListProperty([])

class Screen5(Screen):
    list = ListProperty([])

class ScreenManagement(ScreenManager):
        pass

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


class RVval1(RecycleView):
        def __init__(self, **kwargs):
                super(RVval1, self).__init__(**kwargs)
                #print('removedval:', value2_chsd)
                self.data = [{'text': str(x)} for x in alph]

class RVval2(RecycleView):
        def __init__(self, **kwargs):
                super(RVval2, self).__init__(**kwargs)
                print('removedval:', val1_chsd)
                self.data = [{'text': str(x)} for x in alph]

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

    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 Truej
        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
        if is_selected:
            print("selection changed to {0}".format(rv.data[index]))
            valueselected = format(rv.data[index])
            valueselected = valueselected.replace("{'text': '","")
            valueselected = valueselected.replace("'}","")
            print("valueselected : ",valueselected)
            self.sc3.setvalueselected(valueselected)

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


presentation = Builder.load_file('dfive2.kv')

class DfiveZApp(App):

        def build(self):
                return presentation

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

Файл Kivy

#:import SlideTransition kivy.uix.screenmanager.SlideTransition

ScreenManagement:
    id:screenmgr


    Screen3:
        id: screen_3
        name : "screen3"
        manager: screenmgr

    Screen4:
        id: rv_screen_val1
        name : "screen4"
    Screen5:
        id: rv_screen_val2
        name : "screen5"

<Screen3>:
    BoxLayout:
        orientation: "vertical"
        BoxLayout:
            orientation: "vertical"
            #size_hint_y: 1
            GridLayout:
                cols: 2
                size_hint_y: 2
                Label: 
                    text:"Value1"

                Button:
                    id: val1_name
                    text: 'val1'
                    on_press:
                        root.buttontype('button1')
                        app.root.transition = SlideTransition(direction='left')
                        app.root.current = 'screen4'
                Label: 
                    text:"Value2"
                Button:
                    id: val2_name
                    text: 'val2'
                    on_press:
                        root.buttontype('button2')
                        app.root.transition = SlideTransition(direction='left')
                        app.root.current = 'screen5'
        BoxLayout:
            Label:
                text:root.labeltext
            Button:
                text: 'Submit'
                on_press:
                    root.printselected()
                    #app.root.transition = SlideTransition(direction='left')

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

<RVval1>:
    viewclass: 'SelectableLabel'
    SelectableRecycleBoxLayout:
        default_size: None, dp(56)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
        multiselect: False
        touch_multiselect: False

<RVval2>:
    viewclass: 'SelectableLabel'
    SelectableRecycleBoxLayout:
        default_size: None, dp(56)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
        multiselect: False
        touch_multiselect: False

<Screen4>:
    BoxLayout:
        list: rv_list_val1
        orientation: "vertical"
        RVval1:
            id: rv_list_val1
        Button:
            text: 'Previous screen'
            size_hint: None, None
            size: 150, 50
            #on_press: root.SetText()
            on_release: 
                #root.manager.current = root.manager.previous()
                app.root.transition = SlideTransition(direction='right')
                app.root.current = 'screen3'


<Screen5>:
    BoxLayout:
        list: rv_list_val2
        orientation: "vertical"
        RVval2:
            id: rv_list_val2
        Button:
            text: 'Previous screen'
            size_hint: None, None
            size: 150, 50
            #on_press: root.SetText()
            on_release: 
                #root.manager.current = root.manager.previous()
                app.root.transition = SlideTransition(direction='right')
                app.root.current = 'screen3'

1 Ответ

0 голосов
/ 24 марта 2020

Вы можете создать метод для перезагрузки данных на втором шаге и установить строковое свойство в представлении.

.py file

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager,Screen,SlideTransition,FadeTransition  
from kivy.uix.checkbox import CheckBox
from kivy.properties import ObjectProperty, NumericProperty, BooleanProperty,ListProperty,StringProperty
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.base import runTouchApp
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.recycleview import RecycleView
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.recycleview.views import RecycleDataViewBehavior


alph = ['a','b','c','d','e','f','g','h','i']
sel_values1 = []
val1_chsd = None
val2_chsd = None


class Screen3(Screen):
        #pass
        labeltext = StringProperty('My selection')
        val1 = StringProperty('val1')
        val2 = StringProperty('val2')

        def buttontype(self,types):
                global buttonval
                print("type called :",types)
                if types is "button1":
                        buttonval = "selection1"
                        print ('value set 1',buttonval)
                elif types is "button2":
                        buttonval = "selection2"
                        print ('value set 2',buttonval)

        def setvalueselected(self,sel_value):
                print("Selected value is",sel_value)
                global val1_chsd
                global val2_chsd              
                if buttonval is "selection1":
                        val1_chsd = sel_value
                        val1_name = sel_value
                        print("choosed no. 1",val1_name)
                        self.val1 = val1_name


                if  buttonval is "selection2":
                        val2_chsd = sel_value
                        val2_name = sel_value
                        print("choosed no. 2",val2_name)
                        self.val2 = val2_name

        def printselected(self):
                print("abcdef",val1_chsd,val2_chsd)
                if val1_chsd != None and val2_chsd != None:
                        selected = val1_chsd + '\n' + val2_chsd
                        print ("choosed : ",selected)
                        self.labeltext = selected
                else:
                        print ("Choose all values")


class Screen4(Screen):
    list = ListProperty([])

class Screen5(Screen):
    list = ListProperty([])

class ScreenManagement(ScreenManager):
        pass

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


class RVval1(RecycleView):
        def __init__(self, **kwargs):
                super(RVval1, self).__init__(**kwargs)
                #print('removedval:', value2_chsd)
                self.data = [{'text': str(x)} for x in alph]

class RVval2(RecycleView):
        def __init__(self, **kwargs):
                super(RVval2, self).__init__(**kwargs)
                print('removedval:', val1_chsd)
                self.data = [{'text': str(x)} for x in alph]

        def reload_data(self):
                self.data = [{'text': str(x)} for x in alph if x not in sel_values1]

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

    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 Truej
        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
        if is_selected:
            print("selection changed to {0}".format(rv.data[index]))
            valueselected = format(rv.data[index])
            valueselected = valueselected.replace("{'text': '","")
            valueselected = valueselected.replace("'}","")
            print("valueselected : ",valueselected)
            print(hasattr(rv, "RVval1"))
            if (rv.name == "RVval1"):
                sel_values1.append(valueselected)
            app = App.get_running_app()
            app.root.ids['screen_3'].setvalueselected(valueselected)
            app.root.ids['rv_screen_val2'].ids['rv_list_val2'].reload_data()
        else:
        print("selection removed for {0}".format(rv.data[index-1]))


presentation = Builder.load_file('dfive2.kv')

class DfiveZApp(App):

        def build(self):
                return presentation

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

.kv file

#:import SlideTransition kivy.uix.screenmanager.SlideTransition

ScreenManagement:
    id:screenmgr


    Screen3:
        id: screen_3
        name : "screen3"
        manager: screenmgr

    Screen4:
        id: rv_screen_val1
        name : "screen4"
    Screen5:
        id: rv_screen_val2
        name : "screen5"

<Screen3>:
    BoxLayout:
        orientation: "vertical"
        BoxLayout:
            orientation: "vertical"
            #size_hint_y: 1
            GridLayout:
                cols: 2
                size_hint_y: 2
                Label: 
                    text:"Value1"

                Button:
                    id: val1_name
                    text: root.val1
                    on_press:
                        root.buttontype('button1')
                        app.root.transition = SlideTransition(direction='left')
                        app.root.current = 'screen4'
                Label: 
                    text:"Value2"
                Button:
                    id: val2_name
                    text: root.val2
                    on_press:
                        root.buttontype('button2')
                        app.root.transition = SlideTransition(direction='left')
                        app.root.current = 'screen5'
        BoxLayout:
            Label:
                text:root.labeltext
            Button:
                text: 'Submit'
                on_press:
                    root.printselected()
                    #app.root.transition = SlideTransition(direction='left')

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

<RVval1>:
    viewclass: 'SelectableLabel'
    SelectableRecycleBoxLayout:
        default_size: None, dp(56)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
        multiselect: False
        touch_multiselect: False

<RVval2>:
    viewclass: 'SelectableLabel'
    SelectableRecycleBoxLayout:
        default_size: None, dp(56)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
        multiselect: False
        touch_multiselect: False

<Screen4>:
    BoxLayout:
        list: rv_list_val1
        orientation: "vertical"
        RVval1:
            id: rv_list_val1
            name: 'RVval1'
        Button:
            text: 'Previous screen'
            size_hint: None, None
            size: 150, 50
            #on_press: root.SetText()
            on_release: 
                #root.manager.current = root.manager.previous()
                app.root.transition = SlideTransition(direction='right')
                app.root.current = 'screen3'


<Screen5>:
    BoxLayout:
        list: rv_list_val2
        orientation: "vertical"
        RVval2:
            id: rv_list_val2
            name: 'RVval2'
        Button:
            text: 'Previous screen'
            size_hint: None, None
            size: 150, 50
            #on_press: root.SetText()
            on_release: 
                #root.manager.current = root.manager.previous()
                app.root.transition = SlideTransition(direction='right')
                app.root.current = 'screen3'
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...