跳转至

tkflu.label · FluLabel 标签

文本标签组件。

FluLabel 支持通过 tooltip() 挂一个 Fluent 风格的悬浮提示。

宽度自适应

历史实现的 width 默认是 120px 的固定画布,文本以 anchor="center" 居中绘制。文字一旦比 120px 宽,左右两侧就都被裁掉——例如 FluLabel(root, text="FluLabel(悬停看提示)") 会被显示成 uLabel(悬停看提示)。

现在:调用方不传 width 时,标签会按文本自动撑开(只增不减, 避免文字变化时抖动)。显式传了 width 则完全以显式值为准,行为与旧版一致。

FluLabel

Bases: DDrawWidget, FluToolTipBase, FluGradient, TracedAfter

源代码位于: tkflu\label.py
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
class FluLabel(DDrawWidget, FluToolTipBase, FluGradient, TracedAfter):
    def __init__(
        self, *args, text="", width=None, height=32, font=None, mode="light", **kwargs
    ):
        self._init(mode)

        #: 调用方显式指定的宽度;None 表示"按文本自适应"
        self._fixed_width = width

        super().__init__(*args, width=self._initial_width(args, kwargs, text, width),
                         height=height, **kwargs)

        self.dconfigure(
            text=text,
        )

        from .defs import set_default_font

        set_default_font(font, self.attributes, master=self)

    # ------------------------------------------------------------------
    def _initial_width(self, args, kwargs, text, width):
        """创建画布前先算出一个合理的初始宽度。"""
        if width is not None:
            return width
        if not text:
            return _EMPTY_WIDTH
        from .defs import measure_label_width

        return max(24, measure_label_width(_resolve_master(args, kwargs), text,
                                           padding=_TEXT_PADDING))

    def _init(self, mode):

        from easydict import EasyDict

        self.attributes = EasyDict(
            {
                "text": "",
                "command": None,
                "font": None,
                "text_color": "#1b1b1b",
            }
        )

        self.theme(mode=mode)

    def _fit_to_text(self):
        """文本比画布宽时把画布加宽(只增不减,避免反复触发重排)。

        只在调用方**没有**显式指定宽度时生效。
        """
        if self._fixed_width is not None:
            return
        if not getattr(self, "element_text", None):
            return

        try:
            bbox = self.bbox(self.element_text)
        except Exception:
            return
        if not bbox:
            return  # 尚未映射,量不到

        needed = int(bbox[2] - bbox[0]) + _TEXT_PADDING
        current = self.winfo_reqwidth()
        if needed > current:
            self.config(width=needed)

    def _draw(self, event=None, tempcolor=None):
        super()._draw(event)

        if tempcolor:
            _text_color = tempcolor
        else:
            _text_color = self.attributes.text_color

        if not hasattr(self, "element_text"):
            self.element_text = self.create_text(
                self.winfo_width() / 2,
                self.winfo_height() / 2,
                anchor="center",
                fill=_text_color,
                text=self.attributes.text,
                font=self.attributes.font,
            )
        else:
            self.coords(
                self.element_text, self.winfo_width() / 2, self.winfo_height() / 2
            )
            self.itemconfigure(
                self.element_text,
                fill=_text_color,
                text=self.attributes.text,
                font=self.attributes.font,
            )

        self._fit_to_text()

    def theme(
        self, mode="light", animation_steps: int = None, animation_step_time: int = None
    ):
        from .designs.label import label

        self.mode = mode
        m = label(mode)

        if animation_steps is None:
            from .designs.animation import get_animation_steps

            animation_steps = get_animation_steps()
        if animation_step_time is None:
            from .designs.animation import get_animation_step_time

            animation_step_time = get_animation_step_time()

        if not animation_steps == 0 or not animation_step_time == 0:
            if hasattr(self, "tk"):
                if self.attributes.text_color != m["text_color"]:
                    # 撤销上一轮没跑完的帧,避免迟到的旧颜色盖掉这次的结果
                    self.cancel_traced()
                    text_colors = self.generate_hex2hex(
                        self.attributes.text_color,
                        m["text_color"],
                        steps=animation_steps,
                    )
                    for i in range(animation_steps):

                        def update(ii=i):  # 使用默认参数立即捕获i的值
                            self._draw(tempcolor=text_colors[ii])

                        self.after_traced(i * animation_step_time, update)
                    # 最后一帧是中间色,补一次权威重绘回到目标颜色
                    self.after_traced(
                        animation_steps * animation_step_time + 10,
                        lambda: self._draw(),
                    )
        self.dconfigure(text_color=m["text_color"])
        if hasattr(self, "tk"):
            self._draw()