如何正确缩放 MDIconButton?

How to correctly scale MDIconButton?

我想根据画笔大小缩放 MDIconButtonPushMatrix/PullMatrix 似乎适用于 canvas 中的所有后续小部件,而不仅仅是预期的按钮小部件。

我发现标准 kivy Button 小部件不会发生这种情况,但希望继续使用 kivymd MDIconButton 来制作动画和其他行为/装饰。

目前,我在顶部使用标签为我的按钮添加额外的细节,这使得这个实现在我看来是最直接的。 我想这个问题是由 MDIconButton 继承的一种行为引起的,但还不能准确地找出是哪一种。

from kivy.app import App
from kivy.lang import Builder

from kivymd.button import MDRaisedButton, MDIconButton

class TestApp(App):
    def build(self):
        return Builder.load_string('''
BoxLayout:
    orientation: 'vertical'

    BoxLayout:
        size_hint_y: None
        height: dp(42)
        orientation: 'horizontal'

        ##Button:
        MDIconButton:
            _scale: 1
            on_release: self._scale = (((self._scale*3) + 1) % 3) / 3
            ##text: 'brush'
            icon: 'brush'
            theme_text_color: 'Custom'
            text_color: 1,1,1,1
            canvas.before:
                PushMatrix
                Scale:
                    origin: self.center
                    x: self._scale or 1.
                    y: self._scale or 1.
            canvas.after:
                PopMatrix

    Widget:
        id: palette
        size_hint_y: None
        height: dp(42)
        canvas.before:
            Color:
                rgb: 1,0,0
            Rectangle:
                size: self.size
                pos: self.pos

    Widget:
        id: sketchpad
        canvas.before:
            Color:
                rgb: 1,1,0
            Rectangle:
                size: self.size
                pos: self.pos
''')


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

MDIconButton icon: 'brush' 应在 3 种尺寸之间循环,使其余小部件保持正常尺寸(将 MDIconButton 替换为 Button 并更改 icon:text:).

有没有 better/different 改变图标大小的方法,完全避免这个问题?

您的问题询问如何正确缩放MDIconButton。我不能说这是 correct,但这里有一个 hack 可以实现它。注意icon只是一个字体中的一个字符,所以它的大小可以通过调整字体大小来调整。为此,我扩展了 BoxLayout(仅因为它是您的 root)以包含一个 set_font_size() 方法:

class MyBoxLayout(BoxLayout):
    def set_font_size(self, *args):
        butt = self.ids.mdIconButt
        label = butt.ids.content

        # adjust font size for the icon
        label.font_size *= 1.1

        # adjust the size of the buttons containers
        butt.height *= 1.1
        butt.width *= 1.1
        butt.parent.height *= 1.1

然后,在您的 kv 字符串中:

MyBoxLayout:
    orientation: 'vertical'

    BoxLayout:
        size_hint_y: None
        height: dp(42)
        orientation: 'horizontal'

        ##Button:
        MDIconButton:
            id: mdIconButt  # id to make it easy to find this widget
            on_release: root.set_font_size()  # call the new method
            icon: 'brush'
            theme_text_color: 'Custom'
            text_color: 1,1,1,1
    .
    .
    .

请注意,这是在摆弄 MDIconButton 内部结构,因此预计它会在对 kivyMD.

的任何更改时中断

实际上,您只需将 MDIconButtonon_release 替换为:

即可完成其中的大部分工作
on_release: self.ids.content.font_size *= 1.1

但是只有图标大小发生变化,MDIconButton 及其容器没有变化。