【问题标题】:Change the icon when you click MDIconButton单击 MDIconButton 时更改图标
【发布时间】:2022-10-05 20:53:32
【问题描述】:

你能告诉我如何让点击按钮(MDIconButton)改变图标。 我通过更改 icon 变量尝试了这个:

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

但是在那之后对齐丢失并且图标转到左下角并且无法更改它。

请帮我这么多。

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


【解决方案1】:

下面的示例包含一个MDIconButton,单击它后其图标会发生变化,同时保持其原始大小和位置,如预期的那样。

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 2018-06-07
    • 2021-12-12
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    相关资源
    最近更新 更多