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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605 | class FluRadioBox(FluRadioBoxCanvas, DDrawWidget, FluToolTipBase):
"""Fluent 风格的单选框。
:cvar BOX: 圆环外径(像素)
:cvar GAP: 圆环与标签之间的间距
:cvar PADDING: 控件左右两侧的内边距
"""
#: 圆环外径
BOX = 20
#: 圆环与文字之间的间距
GAP = 8
#: 控件左/右内边距(与 FluCheckBox 一致:Figma 里都是"控件左边缘 + 4")
PADDING = 4
def __init__(
self,
*args,
text: str = "",
value=None,
variable=None,
group: Optional[str] = None,
checked: Optional[bool] = None,
command: Optional[Callable] = None,
font=None,
mode: MODE = "light",
state: STATE = "normal",
width: Optional[Union[int, float]] = None,
height: Union[int, float] = 32,
**kwargs,
) -> None:
"""构造单选框。
:param args: 透传给 :class:`tkinter.Canvas.__init__`
:param text: 标签文字
:param value: 本项在被选中时写进 ``variable`` 的值
:param variable: 共享的 Tk 变量(``StringVar`` / ``IntVar`` …);
与同一变量的其它单选框自动互斥
:param group: 组名;没有 ``variable`` 时按它取一个窗口内共享的变量
:param checked: 初始是否选中。默认 ``None`` 表示"由变量决定"——
变量的值等于 ``value`` 时即选中
:param command: 选中状态变化后的回调,不带参数
:param font: 自定义字体
:param mode: ``"light"`` / ``"dark"``
:param state: ``"normal"`` / ``"disabled"``
:param width: 控件宽度;``None`` 表示按文字自适应(只增不减)
:param height: 控件高度,默认 32
:param kwargs: 其余参数透传给 :class:`tkinter.Canvas.__init__`
:raises ValueError: 同时传了 ``variable`` 和 ``group``
"""
if variable is not None and group is not None:
raise ValueError("variable 与 group 只能二选一")
self.value = value
self._group_key = None
if variable is None and group is not None:
master = _resolve_master(args, kwargs)
if master is not None:
self._group_key, variable = _acquire_group_variable(master, group)
self._variable = variable
self._init(mode, state, checked)
#: 调用方显式指定的宽度;``None`` 表示"按文本自适应"
self._fixed_width = width
super().__init__(
*args,
width=self._initial_width(args, kwargs, text, width),
height=height,
**kwargs,
)
self.dconfigure(text=text, command=command)
set_default_font(font, self.attributes, master=self)
self._trace_id = None
self._syncing = False
self.configure(takefocus=1)
if variable is not None:
self._sync_from_variable()
try:
self._trace_id = variable.trace_add("write", self._on_variable_write)
except Exception:
self._trace_id = None
self.bind("<<Clicked>>", lambda event=None: self.focus_set(), add="+")
self.bind("<<Clicked>>", lambda event=None: self.invoke(), add="+")
self.bind("<space>", lambda event=None: self.invoke(), add="+")
self.bind("<Return>", lambda event=None: self.invoke(), add="+")
self.bind("<Destroy>", self._event_destroy_radio, add="+")
# ------------------------------------------------------------------
# 初始化
# ------------------------------------------------------------------
def _initial_width(self, args, kwargs, text, width):
"""创建画布之前先算出一个合理的初始宽度。"""
if width is not None:
return width
return self._needed_width(_resolve_master(args, kwargs), text)
def _needed_width(self, master, text):
"""按当前文字算出控件需要多宽。"""
width = self.PADDING * 2 + self.BOX
if text:
width += self.GAP + measure_label_width(master, text, padding=0)
return int(width)
def _init(self, mode, state, checked):
"""建立属性字典(此时还没有 Tk 画布,不能碰任何 Tk 调用)。"""
from easydict import EasyDict
self.enter = False
self.button1 = False
self.isfocus = False
self.attributes = EasyDict(
{
"text": "",
"command": None,
"font": None,
"state": "normal",
"checked": bool(checked),
# 下面这组由 designs.radiobox 填充
"back_color": None,
"back_opacity": 0.0,
"border_color": None,
"border_color_opacity": 1.0,
"border_width": RING_WIDTH,
"text_color": "#1b1b1b",
"dot_color": None,
"dot_ratio": 0.5,
"dot_size": DOT_SIZE,
"focus_color": "#000000",
"focus_opacity": 0.0,
"focus_inner_color": "#ffffff",
"focus_inner_opacity": 1.0,
}
)
if checked is not None:
self.attributes.checked = bool(checked)
self.attributes.state = state
self.mode = mode
self._apply_design()
# ------------------------------------------------------------------
# 主题
# ------------------------------------------------------------------
def theme(self, mode=None, state=None):
"""切换主题 / 状态配色。
:param mode: ``"light"`` / ``"dark"``;省略表示沿用当前值
:param state: 交互状态;省略表示沿用当前值
"""
if mode:
self.mode = mode
if state:
self.attributes.state = state
self._apply_design()
def _apply_design(self):
"""按 ``(mode, 交互状态, 勾选态)`` 刷新配色。
与 :class:`~tkflu.checkbox.FluCheckBox` 同理:``_draw()`` 每次都重算配色,
所以过渡帧要靠 :func:`~tkflu.theme_transition.blend_theme_design` 保住,
否则单选按钮会在整屏的渐变里"瞬间跳变"。
"""
design = radiobox_design(
getattr(self, "mode", "light"),
self._visual_state(),
self.attributes.checked,
)
self.dconfigure(blend_theme_design(self, design))
def _visual_state(self):
"""把交互状态位归并成设计规范认识的状态名。"""
if self.attributes.state == "disabled":
return "disabled"
return self.interaction_state()
# ------------------------------------------------------------------
# 分组 / 变量同步
# ------------------------------------------------------------------
@property
def variable(self):
"""本单选框绑定的 Tk 变量(没绑定时为 ``None``)。"""
return self._variable
def _on_variable_write(self, *_args):
"""共享变量被改动(可能是别的单选框改的)→ 跟着刷新。"""
if self._syncing:
return
self._sync_from_variable(notify=True)
def _sync_from_variable(self, notify: bool = False):
"""按共享变量当前的值刷新 ``checked``。
:param notify: 本项**被选中**时是否触发 ``command``
.. note::
只有"变成选中"才会通知,**取消选中不会**。同一个组里换选另一项时,
变量写入会让旧项的监听也回调一次;如果取消选中也发 ``command``,
用户点一次会收到两条回调(旧项 + 新项),而且旧项那条几乎肯定
不是他想要的。
"""
if self._variable is None:
return
try:
current = self._variable.get()
except Exception:
return
checked = str(current) == str(self.value)
if checked == self.attributes.checked:
return
self.attributes.checked = checked
self._apply_design()
self._draw()
if notify and checked:
call_command(self.attributes.command)
# ------------------------------------------------------------------
# 选中状态
# ------------------------------------------------------------------
@property
def checked(self):
"""当前是否被选中。"""
return bool(self.attributes.checked)
@checked.setter
def checked(self, value):
self.set_checked(value)
def set_checked(self, checked: bool = True, notify: bool = False):
"""直接设置选中状态。
:param checked: ``True`` 选中;``False`` 取消选中
:param notify: 是否触发 ``command``,默认 ``False``
绑定变量时,选中会把变量写成 ``value``;取消选中则把变量写成
空字符串(Tk 的惯用做法:谁都不选),从而让同组的其它单选框
一起取消高亮。
"""
checked = bool(checked)
changed = checked != bool(self.attributes.checked)
if self._variable is not None:
self._syncing = True
try:
self._variable.set(self.value if checked else "")
except Exception:
pass
finally:
self._syncing = False
self.attributes.checked = checked
self._apply_design()
self._draw()
if notify and changed:
call_command(self.attributes.command)
def select(self, notify: bool = False):
"""选中本项。"""
self.set_checked(True, notify=notify)
def deselect(self, notify: bool = False):
"""取消选中本项。"""
self.set_checked(False, notify=notify)
def invoke(self):
"""走一遍"用户点击"的完整流程。
已经是选中状态时不做任何事(单选框不能靠再点一下取消,
这是 Windows 的行为);这样也避免重复点选时反复触发 ``command``。
"""
if self.attributes.state == "disabled":
return
self.focus_set()
if self.attributes.checked:
return
self.set_checked(True, notify=True)
# ------------------------------------------------------------------
# 绘制
# ------------------------------------------------------------------
def _draw(self, event: Optional[Event] = None):
"""把单选框画出来(焦点环 + 圆环 + 圆点 + 标签)。"""
super()._draw(event)
# 与 FluCheckBox 同理:每次重绘都按当前状态重算配色,这样
# ``dconfigure(state=...)`` 与 hover/按压都能立刻反映出来。
self._apply_design()
self.delete("all")
width = self.winfo_width()
height = self.winfo_height()
from .designs.renderer import get_renderer
if get_renderer() == 1:
width -= 1
height -= 1
box_x = self.PADDING
box_y = (height - self.BOX) / 2.0
radius = self.BOX / 2.0
if self.isfocus and self.attributes.focus_opacity:
self._draw_focus_ring(box_x, box_y, radius, width, height)
self.element_ring = self.draw_roundrect(
box_x,
box_y,
box_x + self.BOX,
box_y + self.BOX,
radius,
temppath=self.temppath,
temppath2=self.temppath3,
fill=self.attributes.back_color,
fill_opacity=self.attributes.back_opacity,
outline=self.attributes.border_color,
outline_opacity=self.attributes.border_color_opacity,
width=self.attributes.border_width,
)
self._draw_dot(box_x, box_y, radius)
self._draw_label(box_x, height)
self._fit_to_text()
def _draw_focus_ring(self, box_x, box_y, radius, width=None, height=None):
"""画焦点带:贴着整个控件外沿的 3px **两层**带(与 FluCheckBox 一致)。
设计稿里单选框的焦点带是一个 **直径 26 的圆**(控件 20 + 每边 3),
不是圆角矩形。这里用 ``draw_roundrect`` 把圆角取成外径的一半得到正圆。
"""
width = self.winfo_width() if width is None else width
height = self.winfo_height() if height is None else height
margin = FOCUS_MARGIN
# 关注的是"方框那一侧"还是"整个控件":设计稿的 Plain 变体
# (只有圆、没有文字)焦点是 26×26 的圆;带文字时是包住整条的矩形。
if self.attributes.text:
x1, y1 = -margin, -margin
x2, y2 = width + margin, height + margin
outer_radius = FOCUS_RADIUS
else:
x1, y1 = box_x - margin, box_y - margin
x2, y2 = box_x + self.BOX + margin, box_y + self.BOX + margin
outer_radius = (x2 - x1) / 2.0
self.element_focus = self.draw_roundrect(
x1,
y1,
x2,
y2,
outer_radius,
temppath=self.temppath2,
temppath2=self.temppath4,
fill="transparent",
fill_opacity=0.0,
outline=self.attributes.focus_inner_color,
outline_opacity=self.attributes.focus_inner_opacity,
width=FOCUS_INNER_WIDTH + FOCUS_OUTER_WIDTH,
)
self.element_focus_inner = self.draw_roundrect(
x1,
y1,
x2,
y2,
outer_radius,
temppath=self.temppath2,
temppath2=self.temppath4,
fill="transparent",
fill_opacity=0.0,
outline=self.attributes.focus_color,
outline_opacity=self.attributes.focus_opacity,
width=FOCUS_OUTER_WIDTH,
)
def _draw_dot(self, box_x, box_y, radius):
"""画中间的实心圆点(未选中时不画)。
直径取 ``attributes.dot_size`` —— 设计稿里它在四个状态下不一样
(rest 8 / hover 10 / pressed 6 / disabled 8),所以不能按圆环半径
等比推。``dot_ratio`` 只是没有 dot_size 时的兜底。
"""
dot_color = self.attributes.dot_color
if not dot_color:
self.element_dot = None
return
size = float(self.attributes.dot_size or 0) or (
radius * 2.0 * float(self.attributes.dot_ratio or 0.5)
)
dot_radius = size / 2.0
center_x = box_x + self.BOX / 2.0
center_y = box_y + self.BOX / 2.0
self.element_dot = self.draw_roundrect(
center_x - dot_radius,
center_y - dot_radius,
center_x + dot_radius,
center_y + dot_radius,
dot_radius,
temppath=self.temppath,
temppath2=self.temppath3,
fill=dot_color,
fill_opacity=1.0,
outline=None,
outline_opacity=0.0,
width=0,
)
def _draw_label(self, box_x, height):
"""画右侧标签。"""
self.element_text = self.create_text(
box_x + self.BOX + self.GAP,
height / 2.0,
anchor="w",
fill=self.attributes.text_color,
text=self.attributes.text,
font=self.attributes.font,
)
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 = self.PADDING * 2 + self.BOX + self.GAP + int(bbox[2] - bbox[0])
if needed > self.winfo_reqwidth():
self.config(width=needed)
# ------------------------------------------------------------------
# 事件
# ------------------------------------------------------------------
def _event_on_button1(self, event=None):
"""左键按下:禁用时不进入按压态。"""
if self.attributes.state == "disabled":
return
super()._event_on_button1(event)
def _event_off_button1(self, event=None):
"""左键松开:禁用时不发 ``<<Clicked>>``。"""
if self.attributes.state == "disabled":
return
super()._event_off_button1(event)
def _event_destroy_radio(self, event=None):
"""销毁时摘掉变量监听并释放组名引用。"""
if event is not None and getattr(event, "widget", None) is not self:
return
if getattr(self, "_trace_id", None) is not None and self._variable is not None:
try:
self._variable.trace_remove("write", self._trace_id)
except Exception:
pass
self._trace_id = None
if getattr(self, "_group_key", None) is not None:
_release_group_variable(self._group_key)
self._group_key = None
self._variable = None
|