pythonpython-3.xkivy-languagekivymdmd-chip

How to check if a MDChip is selected in KivyMD?


Python 3.9.0

Goal

A way to find if a MDChip is currently selected or not

Problem

Using the check attribute for MDChips to determine if a chip is selected returns True even if the chip is selected or not. I want it to return false when the chip isn't selected.

Example Code

from kivy.lang import Builder
from kivymd.uix.screen import Screen
from kivymd.app import MDApp
from kivymd.uix.menu import MDDropdownMenu
from kivymd.uix.chip import MDChip

KV = '''
MDRaisedButton:
    id: button
    text: "PRESS ME"
    pos_hint: {"center_x": .5, "center_y": .5}
    on_release: app.testing()
'''


class Test(MDApp):
    def build(self):
        self.screen = Screen()
        btn = Builder.load_string(KV)

        self.screen.add_widget(btn)
        return self.screen
    
    def testing(self):
        objects = {0.2 : "Item 1", 0.5 : "Item 2", 0.8 : "Item 3"}
        for pos, item in objects.items():
            chip = MDChip(
                text = item,
                check = True,
                pos_hint = {"center_x":pos, "center_y":0.4},
                on_release = self.fetch
            )
            self.screen.add_widget(chip)

    def fetch(self, chip_instance):
        if chip_instance.check == True:
            print("True")
        else:
            print("False")


Test().run()

KV script is in the main.py file provided above

Expectations

I want to select multiple values from the chips and pass them to a function

The image is taken from this documentation


Solution

  • I think I have a solution to my own problem. (I am very new to KivyMD, and there might be people with better solutions than I have)

    Solution

    def fetch(self, chip_instance):
            if chip_instance.color == [0.12941176470588237, 0.5882352941176471, 0.9529411764705882, 1.0]:
                chip_instance.color = [1,0,0,1]
            else:
                chip_instance.color = [0.12941176470588237, 0.5882352941176471, 0.9529411764705882, 1.0]
    
            if chip_instance.color == [1.0, 0.0, 0.0, 1.0]:
                print("selected")
            else:
                print("not selected")
    

    I am trying to determine which chip is selected based on the color of the chip. I have made 2 if-else block

    If - Else

    1. Changes the color of the chip

    2. Determines which chip is selected based on its color