Обновление списка RecycleView после добавления к данным - PullRequest
0 голосов
/ 15 ноября 2018

Экран «Мой профиль» содержит список RV. Нажав «Добавить профиль», вы попадете на отдельный экран с TextInput и кнопкой «Добавить». После нажатия на кнопку, он добавит вход в файл выбора, из которого список RV получает свои данные. Затем кнопка возвращает вас к экрану профиля.

Моя проблема в том, что список не обновляется с добавленным именем профиля после нажатия кнопки «Добавить» и возврата к экрану профиля, но после закрытия программы и перезагрузки ее, элемент, который мы будем в списке RV.

Экран профиля - это ProfileScreen, а экран добавления профиля - PAddScreen в файле .kv.

home.py

import kivy
kivy.require("1.10.1")
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from modules import roll as r
from modules import profile as p
from modules import modifier as m
from modules import variable as v
from kivy.uix.selectableview import SelectableView
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.uix.textinput import TextInput
from kivy.clock import Clock


# Begin code for Recycle Viewer
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
        print("View Refreshed")
        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):
            print("Touched")
            return True
        if self.collide_point(*touch.pos) and self.selectable:
            print("Touched 2")
            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]))
            print("Applied")

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


class RV(RecycleView):
    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        # self.data = [{'text': str(x)} for x in range(100)]
        self.data = [{'text': str(x)} for x in p.PickleLoadProfile.zip1]


# Begin code for screen manager
class ProfileScreen(Screen):
    pass


class RollScreen(Screen):
    pass


class ModifierScreen(Screen):
    pass


class VariableScreen(Screen):
    pass


class PAddScreen(Screen):

    def addprofile(self, pname):
        p.Profile.add(pname)


class IAddScreen(Screen):
    pass


class ScreenManagement(ScreenManager):
    pass


pres = Builder.load_file("main.kv")


class MainApp(App):

    def build(self):
        return pres


if __name__ == "__main__":
    MainApp().run()

main.kv

#: import FadeTransition kivy.uix.screenmanager.FadeTransition
#: import Profile profile

ScreenManagement:
    transition: FadeTransition()
    ProfileScreen:
    PAddScreen:
    RollScreen:
    IAddScreen:
    ModifierScreen:
    VariableScreen:


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

<RV>:

<ProfileScreen>:
    name: "profile"
    id: profiles

    BoxLayout:
        orientation: 'vertical'
        BoxLayout:
            orientation: 'vertical'
            size_hint_y: .08
            Label:
                font_size: self.height - 2
                text: "Profiles"
                bold: True
                canvas.before:
                    Color:
                        rgba: (.25, .25, .25, 1)
                    Rectangle:
                        pos: self.pos
                        size: self.size
        BoxLayout:
            id: "rv"
            orientation: 'vertical'
            size_hint_y: .71
            #BoxLayout:
            RV:
                viewclass: 'SelectableLabel'
                id: RVTest
                SelectableRecycleBoxLayout:
                    id: RVList
                    spacing: 4
                    default_size: None, root.height *.08
                    default_size_hint: 1, None
                    size_hint: 1, None
                    height: self.minimum_height
                    orientation: 'vertical'
                    multiselect: False
                    touch_multiselect: False
        BoxLayout:
            orientation: 'horizontal'
            size_hint_y: .07
            Button:
                on_release: app.root.current = "roll"
                text: "Open"
                font_size: self.height *.7
        BoxLayout:
            orientation: 'horizontal'
            size_hint_y: .07
            Button:
                on_release: app.root.current = "padd"
                text: "Add Profile"
                font_size: self.height *.7
            Button:
                on_release: app.root.current = "roll"
                text: "Remove Profile"
                font_size: self.height *.7
        BoxLayout:
            orientation: 'horizontal'
            size_hint_y: .07
            Button:
                on_release: app.root.current = "variable"
                text: "Variables"
                font_size: self.height *.7
            Button:
                on_release: app.root.current = "modifier"
                text: "Modifiers"
                font_size: self.height *.7

<RollScreen>:
    name:"roll"
    BoxLayout:
        orientation: 'vertical'
        BoxLayout:
            orientation: 'vertical'
            size_hint_y: .08
            Label:
                font_size: self.height *.8
                text: "Rolls"
        BoxLayout:
            orientation: 'vertical'
            size_hint_y: .84
        BoxLayout:
            orientation: 'horizontal'
            size_hint_y: .08
            BoxLayout:
                Button:
                    on_release: app.root.current = "profile"
                    text: "Profile"
                    font_size: 15
                Button:
                    on_release: app.root.current = "variable"
                    text: "Variables"
                    font_size: 15
                Button:
                    on_release: app.root.current = "modifier"
                    text: "Modifiers"
                    font_size: 15

<VariableScreen>:
    name:"variable"
    BoxLayout:
        orientation: 'vertical'
        BoxLayout:
            orientation: 'vertical'
            size_hint_y: .08
            Label:
                font_size: 20
                text: "Variables"
        BoxLayout:
            orientation: 'vertical'
            size_hint_y: .84
        BoxLayout:
            orientation: 'horizontal'
            size_hint_y: .08
            BoxLayout:
                Button:
                    on_release: app.root.current = "profile"
                    text: "Profile"
                    font_size: 15
                Button:
                    on_release: app.root.current = "roll"
                    text: "Rolls"
                    font_size: 15
                Button:
                    on_release: app.root.current = "modifier"
                    text: "Modifiers"
                    font_size: 15

<ModifierScreen>:
    name:"modifier"
    BoxLayout:
        orientation: 'vertical'
        BoxLayout:
            orientation: 'vertical'
            size_hint_y: .08
            Label:
                font_size: 20
                text: "Modifiers"
        BoxLayout:
            orientation: 'vertical'
            size_hint_y: .84
        BoxLayout:
            orientation: 'horizontal'
            size_hint_y: .08
            BoxLayout:
                Button:
                    on_release: app.root.current = "profile"
                    text: "Profile"
                    font_size: 15
                Button:
                    on_release: app.root.current = "roll"
                    text: "Rolls"
                    font_size: 15
                Button:
                    on_release: app.root.current = "variable"
                    text: "Variables"
                    font_size: 15

<PAddScreen>:
    name: "padd"
    BoxLayout:
        orientation: 'vertical'
        BoxLayout:
            size_hint_y: .1
        BoxLayout:
            size_hint_y: .1
            BoxLayout:
                size_hint_x: .1
                size_hint_y: None
            BoxLayout:
                TextInput:
                    id: apinput
                    hint_text: "Enter profile name"
                    pos: self.pos
                    size: self.size
                    text: ""
                    multiline: False
                    font_size: self.height*.5
            BoxLayout:
                size_hint_x: .1
        BoxLayout:
            orientation: 'horizontal'
            size_hint_y: .8
        BoxLayout:
            size_hint_y: .1
            orientation: 'horizontal'
            Button:
                on_press: root.addprofile(apinput.text)
                on_release:
                on_release: app.root.current = "profile"
                text: "Add"
                font_size: self.height *.8
            Button:
                on_release: app.root.current = "profile"
                text: "Cancel"
                font_size: self.height *.8

<IAddScreen>:
    name: "iadd"

profile.py

import pickle


class PickleLoadProfile:
    try:
        with open('main.kv.pkl', 'rb') as f:
            zip1 = pickle.load(f)

    except:
        zip1 = ""
        pass


class Profile:
    proList = ['']
    proCount = ['']

    def add(name):

        pl = Profile.proList
        pc = Profile.proCount

        try:
            with open('main.kv.pkl', 'rb') as f:
                zip1 = pickle.load(f)

        except:
            pass

        if name == '':
            pass

        else:
            try:
                pl = list(zip1.keys())
                pc = list(zip1.values())
                (pl, pc) = zip(*zip1.items())
                pl = list(pl)
                pc = list(pc)
            except:
                print("Try 1 failed")
                print(pl, pc)
                pass
            if pl[0] == '':
                pl[0] = name
                pc[0] = str((len(pl)))
            else:
                pl.append(name)
                # pl.append(input("Enter profile name: "))
                pc.append(str((len(pl))))
            Profile.proList = pl
            Profile.proCount = pc
            zip1 = dict(zip(pl, pc))
            print(zip1)
            with open('main.kv.pkl', 'wb') as f:
                pickle.dump(zip1, f)



    def remove():

        pl = Profile.proList
        pc = Profile.proCount

        try:
            with open('main.kv.pkl', 'rb') as f:
                zip1 = pickle.load(f)

                pl = list(zip1.keys())
                (pl, pc) = zip(*zip1.items())
                pl = list(pl)

        except pickle.UnpicklingError as e:
            pass

        except (AttributeError, EOFError, ImportError, IndexError) as e:
            pass

        except Exception as e:
            return

        if pl[0] == '':
            return print("No profiles have been made.")

        else:
            print(pl)
            r = input("Who would you like to remove: ")

            if r == "":
                print("You have to type a name: ")
                Profile.remove()

            else:
                try:
                    del zip1[r]
                except:
                    print("Profile does not exist")
                    pass

        pl = list(zip1.keys())
        pc = list(zip1.values())
        (pl, pc) = zip(*zip1.items())
        pl = list(pl)
        pc = list(pc)
        for x in range(len(pc)):
            pc[x] = x+1

        zip1 = dict(zip(pl, pc))
        print(zip1)
        with open('main.kv.pkl', 'wb') as f:
            pickle.dump(zip1, f)

    def show():

        try:
            with open('main.kv.pkl', 'rb') as f:
                zip1 = pickle.load(f)

        except pickle.UnpicklingError as e:
            pass

        except (AttributeError, EOFError, ImportError, IndexError) as e:
            pass

        except Exception as e:
            return
        print(zip1)


if __name__ == '__main__':
    do = input("Would you like to add, remove, or show: ")

    if do == "add":
        Profile.add()
    elif do == "remove":
        Profile.remove()
    elif do == "show":
        Profile.show()
...