如何更改回收视图中所选项目的背景颜色。我也希望它自动选择第一个项目(白色背景)

时间:2020-12-26 14:04:39

标签: python python-3.x kivy kivy-language kivymd

recycleview 自动选择最后一个项目我希望它自己选择第一个项目 如果我点击任何其他或第一个它应该改变所选项目的 bcolor。 而且无论我在“pos_hint:”中输入什么值,它都不会改变文本框和按钮的位置。 我也尝试将这些属性放入 Gridlayout 但没有任何变化

.py 代码

class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior,
                                 RecycleGridLayout):
    ''' 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)

    txt_input = ObjectProperty(None)
    stock_name = ObjectProperty(None)
    stock_symbol = ObjectProperty(None)
    purchase_price = ObjectProperty(None)
    stop_loss = ObjectProperty(None)
    bcolor = ListProperty([0, 1, 1, 1])
    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
        if is_selected:

            # App.get_running_app().root.widget_1.ids.txt_input1.text = str(rv.data[index].get("text"))
            xx =str(rv.data[index].get("text"))
            if (xx.find('(NSI)') != -1):
                x,y = xx.split(" (NSI)")
                add_sym = '.NS'
            else:
                x,y = xx.split(" (BSE)")
                add_sym = '.BO'
            print(xx)
            print(x)

            App.get_running_app().root.get_screen('body_screen').widget_1.ids.stock_name.text = x
            f = pd.read_csv("Stock Tickers.csv", encoding="ISO-8859-1", engine='python')
            fl = len(f.index)
            file = pd.DataFrame(f, columns=['Symbols', 'Name', 'Exchange'])


            for i in range(fl):
                for index in range(1):
                    columnSeriesObj_sym = file.iloc[:, 0]
                    columnSeriesObj1 = file.iloc[:, 1]
                    columnSeriesObj_ex = file.iloc[:, 2]
                    before_sym,b = columnSeriesObj_sym.values[i].split('.')


                    if columnSeriesObj1.values[i] == App.get_running_app().root.get_screen('body_screen').widget_1.ids.stock_name.text:
                        App.get_running_app().root.get_screen('body_screen').widget_1.ids.stock_symbol.text = before_sym + add_sym




class RV(RecycleView):
    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)


class DropDownWidget(GridLayout):
    txt_input = ObjectProperty()
    rv = ObjectProperty()

    stock_name = ObjectProperty(None)
    stock_symbol = ObjectProperty(None)
    purchase_price = ObjectProperty(None)
    stop_loss = ObjectProperty(None)


    def btn_input(self):

        end = datetime.today().date()
        start = end


        print("Stock Name:", App.get_running_app().root.get_screen('body_screen').widget_1.ids.stock_name.text,
              "Stock Symbol:", App.get_running_app().root.get_screen('body_screen').widget_1.ids.stock_symbol.text)
        print("Purchase Price:", App.get_running_app().root.get_screen('body_screen').widget_1.ids.purchase_price.text,
              "Stop Loss(%):", App.get_running_app().root.get_screen('body_screen').widget_1.ids.stop_loss.text)

        # write data to csv file


        file_name = username + "_stoploss.csv"
        if path.exists(file_name):
            with open(file_name, "a+", newline='')as newFile:
                fieldnames = ["Stock Name", "Stock Symbol", "Purchase Price", "Stop Loss(%)"]
                newFileWriter = csv.DictWriter(newFile, fieldnames=fieldnames)
                newFileWriter.writerow({"Stock Name": App.get_running_app().root.get_screen('body_screen').widget_1.ids.stock_name.text,
                                        "Stock Symbol": App.get_running_app().root.get_screen('body_screen').widget_1.ids.stock_symbol.text,
                                        "Purchase Price": App.get_running_app().root.get_screen('body_screen').widget_1.ids.purchase_price.text,
                                        "Stop Loss(%)": App.get_running_app().root.get_screen('body_screen').widget_1.ids.stop_loss.text})

        else:
            myFile = open(file_name, 'w+',newline='')
            myData = [["Stock Name", "Stock Symbol", "Purchase Price", "Stop Loss(%)"],
                      [App.get_running_app().root.get_screen('body_screen').widget_1.ids.stock_name.text,
                       App.get_running_app().root.get_screen('body_screen').widget_1.ids.stock_symbol.text,
                       App.get_running_app().root.get_screen('body_screen').widget_1.ids.purchase_price.text,
                       App.get_running_app().root.get_screen('body_screen').widget_1.ids.stop_loss.text]]

            with myFile:
                writer = csv.writer(myFile)
                writer.writerows(myData)

        df = web.DataReader(App.get_running_app().root.get_screen('body_screen').widget_1.ids.stock_symbol.text, 'yahoo', start, end)
        print(df.tail())
        App.get_running_app().root.get_screen('body_screen').widget_1.ids.txt_input.text = ""
        App.get_running_app().root.get_screen('body_screen').widget_1.ids.stock_name.text = ""
        App.get_running_app().root.get_screen('body_screen').widget_1.ids.stock_symbol.text = ""
        App.get_running_app().root.get_screen('body_screen').widget_1.ids.purchase_price.text = ""
        App.get_running_app().root.get_screen('body_screen').widget_1.ids.stop_loss.text = ""


class MyTextInput(TextInput):
    txt_input = ObjectProperty()

    flt_list = ObjectProperty()
    word_list = ListProperty()
    stock_name = ObjectProperty(None)
    stock_symbol = ObjectProperty(None)
    purchase_price = ObjectProperty(None)
    stop_loss = ObjectProperty(None)
    # this is the variable storing the number to which the look-up will start
    starting_no = NumericProperty()
    suggestion_text = ''

    def __init__(self, **kwargs):
        super(MyTextInput, self).__init__(**kwargs)

    def on_text(self, instance, value):
        # find all the occurrence of the word

        self.parent.parent.ids.rv.data = []
        if len(value) != 0:
            matches = [word for word in self.word_list if word.lower().find(value.lower()) != -1]

        # display the data in the recycleview
            display_data = []

            for i in matches:
                display_data.append({'text': i})
            self.parent.parent.ids.rv.data = display_data

            # ensure the size is okay
            if len(matches) <= 10:
                self.parent.height = (50 + (len(matches) * 20))
            else:
                self.parent.height = 240

    def keyboard_on_key_down(self, window, keycode, text, modifiers):
        if self.suggestion_text and keycode[1] == 'tab':
            self.insert_text(self.suggestion_text + ' ')
            return True
        return super(MyTextInput, self).keyboard_on_key_down(window, keycode, text, modifiers)


class Body(Screen):
    def __init__(self, **kwargs):
        super(Body, self).__init__(**kwargs)


        f = pd.read_csv("Stock Tickers.csv", encoding = "ISO-8859-1", engine='python')
        fl = len(f.index)
        file = pd.DataFrame(f, columns=['Symbols', 'Name', 'Exchange'])

        wl = []
        for i in range(fl):
            for index in range(1):

                columnSeriesObj = file.iloc[:, 1]
                self.columnSeriesObj_ex = file.iloc[:, 2]


                wl.append(columnSeriesObj.values[i] + " (" + self.columnSeriesObj_ex.values[i] + ")")


        tp = tuple(wl)
        print("File is loaded")


        self.widget_1 = DropDownWidget(pos_hint={'center_x': .5, 'center_y': .5},
                                       size_hint=(None, None), size=(600, 60))
        self.widget_1.ids.txt_input.word_list = wl
        self.widget_1.ids.txt_input.starting_no = 3
        self.add_widget(self.widget_1)

.kv 代码

<Body>:
    name: 'body_screen'
    canvas.before:
        Color:
            rgba: 188/255, 143/255, 145/255, 1

        Rectangle:
            pos: self.pos
            size: self.size


<DropDownWidget>:
    cols:3
    id: DropDownWidget
    size_hint:(0.5,1)
    pos_hint: {'center_x': 50.5, 'center_y': 1.5}
    row_force_default : True
    row_default_height : 200
    col_force_default : True
    col_default_width : 550

    spacing: '20dp'
    GridLayout:

        canvas:
            Color:
                rgba:(1, 1, 1, 1)



        cols:2
        stock_name: stock_name
        stock_symbol: stock_symbol
        purchase_price: purchase_price
        stop_loss: stop_loss

        txt_input: txt_input
        rv: rv


        MyTextInput:
            id: txt_input


        RV:
            id: rv


        Label:
            text: "Stock Name: "

        TextInput:
            id: stock_name
            readonly: True
            multiline:False

        Label:
            text: "Stock Symbol: "

        TextInput:
            id: stock_symbol
            readonly: True
            multiline:False

        Label:
            text: "Purchase Price: "

        TextInput:
            id: purchase_price
            input_filter: 'int'
            multiline:False

        Label:
            text: "Stop Loss(%): "


        TextInput:
            id: stop_loss
            input_filter: 'int'
            multiline:False

        Button:
            text:"Submit"

            on_press: root.btn_input()
        Button:
            text:"Back"

            on_press: root.parent.manager.current = 'option_screen'




<MyTextInput>:
    id: MyTextInput

    readonly: False
    multiline: False

<SelectableLabel>:

    id: SelectableLabel

    bcolor:  root.bcolor
    # Draw a background to indicate selection
    color: 0,0,0,1
    canvas.before:
        Color:
            rgba: (1, 1, 1, .5) if self.selected else self.bcolor
        Rectangle:
            # pos: self.pos
            size: self.size

<RV>:


    canvas:
        Color:
            rgba: 0,0,0,.2

        Line:
            rectangle: self.x +3 , self.y, self.width - 2, self.height -2


    bar_width: 20
    scroll_type:['bars']
    viewclass: 'SelectableLabel'
    SelectableRecycleBoxLayout:
        cols:1
        default_size: None, dp(20)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
        multiselect: False

1 个答案:

答案 0 :(得分:0)

最后我解决了它。 在弄乱了代码之后,我终于找到了它。这是一个简单的解决方案

只需更改kv代码

来自

<SelectableLabel>:

    id: SelectableLabel

    bcolor:  root.bcolor
    # Draw a background to indicate selection
    color: 0,0,0,1
    canvas.before:
        Color:
            rgba: (1, 1, 1, .5) if self.selected else self.bcolor
        Rectangle:
            # pos: self.pos
            size: self.size

<SelectableLabel>:

    id: SelectableLabel


    
    canvas.after:

        Color:
            rgba: (.0, 0.9, .1, .3) if self.selected else (1, 1, 1, .1)
        Rectangle:
            pos: self.pos
            size: self.size