Home > database >  Change the icon when you click MDIconButton
Change the icon when you click MDIconButton

Time:10-06

could you tell me how to make clicking the button (MDIconButton) change the icon. I tried this by changing the icon variable:

class MyButton(MDIconButton):
    def __init__(self):
        super().__init__(*args, **kwargs)
        self.icon = "path to first image"
        self.alternative = "path to second image"
        self.icon_size = 300
        self.radius = 30
        self.size_hint = [.05, .05]

    def on_press(self):
        self.icon, self.alternative = self.alternative, self.icon

But after that the alignment is lost and the icon goes to the bottom left corner and there is no way to change it.

Please help me so much.

CodePudding user response:

The following example contains an MDIconButton, whose icon changes after clicking it, while keeping its original size and position, as intended.

from kivy.uix.boxlayout import BoxLayout
from kivymd.app import MDApp
from kivy.lang import Builder

Builder.load_string('''
<UpdateIcon>:
    orientation: 'vertical'

    MDIconButton:
        id: iconButton
        icon: 'language-python'
        pos_hint: {'x':.5, 'y':.5}
        size_hint: (.05, .05)
        icon_size: '300sp'
        on_press: root.updateIcon('android')
 ''')

class UpdateIcon(BoxLayout):
    def __init__(self, **kwargs):
        super(UpdateIcon,self).__init__(**kwargs)
        pass

    def updateIcon(self, newIcon):
        self.ids.iconButton.icon = newIcon
        
class TestApp(MDApp):
    def build(self):
        self.title = "Change Icon"
        return UpdateIcon()

if __name__ == '__main__':
    TestApp().run()
  • Related