Shourov
Shourov

Reputation: 69

How to change List item icon using a function in kivymd?

I am a beginner in kivymd. I was trying to create a functionality in my project. In this I need to change icon of OneLineIconListItem as well as its text. I can easily change the the text. But still unable to change the icon. Here is the portion of my problem from code.

from kivy.lang import Builder
from kivymd.app import MDApp
from kivymd.uix.list import OneLineIconListItem,IconLeftWidget

KV = """
MDScreen:
    ScrollView:
        pos_hint : {"center_x": 0.5, 'center_y':0.3}
        MDList:
            OneLineIconListItem:
                id: control_panel
                text: 'Message'
                
                IconLeftWidget:
                    icon:'android-messages'
    MDRectangleFlatButton:
        text: "change"
        user_font_size: "30sp"
        pos_hint: {'center_x':0.5, 'center_y':0.5}
        on_release: 
            app.demoFunction()
"""

class DemoApp(MDApp):
    def build(self):
        self.screen = Builder.load_string(KV)
        return self.screen

    def demoFunction(self):
        self.root.ids.control_panel.text = 'Control panel'
        self.root.ids.control_panel.add_widget(IconLeftWidget(icon='account'))

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

When I press the button the Icon is not changing, it is adding a new icon. How can I change the icon on pressing the button?

Upvotes: 0

Views: 1157

Answers (1)

user13676212
user13676212

Reputation:

Use:

from kivy.lang import Builder
from kivymd.app import MDApp
from kivymd.uix.list import OneLineIconListItem,IconLeftWidget

KV = """
MDScreen:
    ScrollView:
        pos_hint : {"center_x": 0.5, 'center_y':0.3}
        MDList:
            OneLineIconListItem:
                id: control_panel
                text: 'Message'
                
                IconLeftWidget:
                    id: jbsidis
                    icon:'android-messages'
    MDRectangleFlatButton:
        text: "change"
        user_font_size: "30sp"
        pos_hint: {'center_x':0.5, 'center_y':0.5}
        on_release: 
            app.demoFunction()
"""

class DemoAppjbsidis(MDApp):
    def build(self):
        self.screen = Builder.load_string(KV)
        return self.screen

    def demoFunction(self):
        if self.root.ids.jbsidis.icon=="android-messages":
            self.root.ids.jbsidis.icon="account"
            self.root.ids.control_panel.text="New text hereee, icon is account"
            return 0
        if self.root.ids.jbsidis.icon=="account":
            self.root.ids.jbsidis.icon="android-messages"
            self.root.ids.control_panel.text="New text hereee, icon is android-messages"
            return 0

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

Pictures: enter image description here

enter image description here

enter image description here

Upvotes: 1

Related Questions