-
Notifications
You must be signed in to change notification settings - Fork 8
/
tkintertools.py
1452 lines (1245 loc) · 53.9 KB
/
tkintertools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
tkintertools
============
The tkindertools module is an auxiliary module of the tkinder module.
Provides
--------
* Transparent, rounded and customized widgets
* Automatic control of picture size and widget size
* Scalable png pictures and playable gif pictures
* Regular mobile widgets and canvas interfaces
* Gradient colors and contrast colors
* Text with controllable length and alignment
* Convenient, inheritable singleton pattern class
* Display clear window and its contents
Contents
--------
* Container Widget: `Tk`, `Toplevel`, `Canvas`
* Virtual Canvas Widget: `CanvasLabel`, `CanvasButton`, `CanvasEntry`, `CanvasText`, `ProcessBar`
* Tool Class: `PhotoImage`, `Singleton`
* Tool Function: `move`, `text`, `color`
More
----
* GitCode: https://gitcode.net/weixin_62651706/tkintertools
* GitHub(Mirror): https://github.com/392126563/tkintertools
* Gitee(Mirror): https://gitee.com/xiaokang-2022/tkintertools
* Tutorials: https://xiaokang2022.blog.csdn.net/article/details/127374661
"""
import sys # 检测 Python 版本
if sys.version_info < (3, 10):
# 版本检测,低版本缺失部分语法
raise RuntimeError('\033[36mPython version is too low!\033[0m\a')
import math # 数学函数
import tkinter # 基础模块
from ctypes import OleDLL # DPI兼容
from fractions import Fraction # 图片缩放
from typing import Generator, Iterable, Literal, Self, Type # 类型提示
__author__ = 'Xiaokang2022'
__version__ = '2.5.9.5'
__all__ = [
'Tk',
'Toplevel',
'Canvas',
'CanvasLabel',
'CanvasButton',
'CanvasEntry',
'CanvasText',
'ProcessBar',
'PhotoImage',
'Singleton',
'move',
'text',
'color'
]
S = OleDLL('shcore').GetScaleFactorForDevice(0)/100 # 屏幕缩放因子
PROCESS_SYSTEM_DPI_AWARE = 1 # DPI级别
COLOR_BUTTON_FILL = '#E1E1E1', '#E5F1FB', '#CCE4F7', '#F0F0F0' # 默认的按钮内部颜色
COLOR_BUTTON_OUTLINE = '#C0C0C0', '#288CDB', '#4884B4', '#D5D5D5' # 默认的按钮外框颜色
COLOR_TEXT_FILL = '#FFFFFF', '#FFFFFF', '#FFFFFF', '#F0F0F0' # 默认的文本内部颜色
COLOR_TEXT_OUTLINE = '#C0C0C0', '#414141', '#288CDB', '#D5D5D5' # 默认的文本外框颜色
COLOR_TEXT = '#000000', '#000000', '#000000', '#A3A3A3' # 默认的文本颜色
COLOR_NONE = '', '', '', '' # 透明颜色
COLOR_BAR = '#E1E1E1', '#06b025' # 默认的进度条颜色
BORDERWIDTH = 1 # 默认控件外框宽度
CURSOR = '│' # 文本光标
FONT = '楷体', 15 # 默认字体
LIMIT = -1 # 默认文本长度
RADIUS = 0 # 默认控件圆角半径
FRAMES = 60 # 默认帧数
OleDLL('shcore').SetProcessDpiAwareness(PROCESS_SYSTEM_DPI_AWARE) # 设置DPI级别
class Tk(tkinter.Tk):
""" 创建窗口,并处理部分`Canvas`类绑定的关联事件及缩放操作 """
def __init__(
self: Self,
title: str | None = None,
width: int | None = None,
height: int | None = None,
x: int | None = None,
y: int | None = None,
shutdown=None, # type: function | None
**kw
) -> None:
"""
`title`: 窗口标题
`width`: 窗口宽度(单位:像素)
`height`: 窗口高度
`x`: 窗口左上角横坐标(单位:像素)
`y`: 窗口左上角纵坐标
`shutdown`: 关闭窗口之前执行的函数(会覆盖原关闭操作)
`**kw`: 与 tkinter.Tk 类的参数相同
"""
if type(self) == Tk: # NOTE:方便后面的 Toplevel 类继承
tkinter.Tk.__init__(self, **kw)
self.width: list[int] = [100, 1] # [初始宽度, 当前宽度]
self.height: list[int] = [100, 1] # [初始高度, 当前高度]
self._canvas: list[Canvas] = [] # 子画布列表
if width and height:
if x != None and y != None:
self.geometry('%dx%d+%d+%d' % (width, height, x, y))
else:
self.geometry('%dx%d' % (width, height))
self.title(title if title else None)
self.protocol('WM_DELETE_WINDOW', shutdown if shutdown else None)
self.bind('<Configure>', lambda _: self.__zoom()) # 开启窗口缩放检测
self.bind('<Any-Key>', self.__input) # 绑定键盘输入字符(代码顺序不可错)
self.bind('<Control-v>', lambda _: self.__paste()) # 绑定粘贴快捷键
def canvas(self: Self) -> tuple:
""" `Tk`类的`Canvas`元组 """
return tuple(self._canvas)
def __zoom(self: Self) -> None:
""" 缩放检测 """
width, height = map(int, self.geometry().split('+')[0].split('x'))
# NOTE: 此处必须用 geometry 方法,直接用 Event 或者 winfo 会有画面异常的 bug
if (width, height) == (self.width[1], self.height[1]): # 没有大小的改变
return
for canvas in self._canvas:
if canvas.expand and canvas._lock:
canvas.zoom(width/self.width[1], height/self.height[1])
self.width[1], self.height[1] = width, height # 更新窗口当前的宽高值
def __input(self: Self, event: tkinter.Event) -> None:
""" 键盘输入字符事件 """
for canvas in self._canvas:
if canvas._lock:
for widget in canvas._widget[::-1]:
if widget.live and isinstance(widget, _TextWidget):
if widget.input(event):
return
def __paste(self: Self) -> None:
""" 快捷键粘贴事件 """
for canvas in self._canvas:
if canvas._lock:
for widget in canvas._widget[::-1]:
if widget.live and isinstance(widget, _TextWidget):
if widget.paste():
return
def wm_maxsize(self: Self, width: int | None = None, height: int | None = None) -> tuple[int, int] | None:
# 重写:兼容不同的DPI缩放
if width:
return tkinter.Tk.wm_maxsize(self, round(width*S), round(height*S))
return tuple(i/S for i in tkinter.Tk.wm_maxsize(self))
def wm_minsize(self: Self, width: int | None = None, height: int | None = None) -> tuple[int, int] | None:
# 重写:兼容不同的DPI缩放
if width:
return tkinter.Tk.wm_minsize(self, round(width*S), round(height*S))
return tuple(i/S for i in tkinter.Tk.wm_minsize(self))
def wm_geometry(self: Self, newGeometry: str | None = None) -> str | None:
# 重写: 添加修改初始宽高值的功能并兼容不同的DPI缩放
if newGeometry:
width, height, _width, _height, * \
_ = map(int, (newGeometry+'+0+0').replace('+', 'x').split('x'))
self.width, self.height = [width]*2, [height]*2
geometry = '%dx%d+%d+%d' % (width*S, height*S, _width, _height)
if not _:
geometry = geometry.split('+')[0]
return tkinter.Tk.wm_geometry(self, geometry)
geometry = tkinter.Tk.wm_geometry(self, newGeometry)
width, height, _width, _height, * \
_ = map(int, (geometry+'+0+0').replace('+', 'x').split('x'))
return '%dx%d+%d+%d' % (width/S, height/S, _width, _height)
maxsize, minsize, geometry = wm_maxsize, wm_minsize, wm_geometry
class Toplevel(tkinter.Toplevel, Tk):
""" 类似于`tkinter.Toplevel`,同时增加了`Tk`的功能 """
def __init__(
self: Self,
master: Tk,
title: str | None = None,
width: int | None = None,
height: int | None = None,
x: int | None = None,
y: int | None = None,
shutdown=None, # type: function | None
**kw
) -> None:
"""
`master`: 父窗口
`title`: 窗口标题
`width`: 窗口宽度(单位:像素)
`height`: 窗口高度
`x`: 窗口左上角横坐标(单位:像素)
`y`: 窗口左上角纵坐标
`shutdown`: 关闭窗口之前执行的函数(会覆盖关闭操作)
`**kw`: 与 tkinter.Toplevel 类的参数相同
"""
tkinter.Toplevel.__init__(self, master, **kw)
Tk.__init__(self, title, width, height, x, y, shutdown, **kw)
self.focus_set()
class Canvas(tkinter.Canvas):
""" 用于承载虚拟的画布控件,并处理部分绑定事件 """
def __init__(
self: Self,
master: Tk,
width: int,
height: int,
lock: bool = True,
expand: bool = True,
**kw
) -> None:
"""
`master`: 父控件
`width`: 画布宽度
`height`: 画布高度
`lock`: 画布内控件的功能锁(False时功能暂时失效)
`expand`: 画布内控件是否能缩放
`**kw`: 与 tkinter.Canvas 类的参数相同
"""
self.width = [width]*2 # [初始宽度, 当前宽度]
self.height = [height]*2 # [初始高度, 当前高度]
self._lock = lock
self.expand = expand
self.rate_x = 1. # 横向放缩比率
self.rate_y = 1. # 纵向放缩比率
self._widget: list[_BaseWidget] = [] # 子控件列表(与事件绑定有关)
self._font = {} # type: dict[tkinter._CanvasItemId, float]
self._image = {} # type: dict[tkinter._CanvasItemId, list]
tkinter.Canvas.__init__(
self, master, width=width*S, height=height*S, highlightthickness=0, **kw)
master._canvas.append(self) # 将实例添加到 Tk 的画布列表中
self.bind('<Motion>', self.__touch) # 绑定鼠标触碰控件
self.bind('<Button-1>', self.__press) # 绑定鼠标左键按下
self.bind('<B1-Motion>', self.__press) # 绑定鼠标左键按下移动
self.bind('<MouseWheel>', self.__mousewheel) # 绑定鼠标滚轮滚动
self.bind('<ButtonRelease-1>', self.__release) # 绑定鼠标左键松开
@property
def lock(self) -> bool:
return self._lock
@lock.setter
def lock(self, value: bool) -> None:
self._lock = value
if value and self.expand:
self.zoom()
def widget(self: Self) -> tuple:
""" `Canvas`类的子控件元组 """
return tuple(self._widget)
def zoom(self: Self, rate_x: float | None = None, rate_y: float | None = None) -> None:
"""
缩放画布及其内部的所有元素
`rate_x`: 横向缩放比率,默认值表示自动更新缩放(根据窗口缩放程度)
`rate_y`: 纵向缩放比率,默认值同上
"""
if not rate_x:
rate_x = self.master.width[1]/self.master.width[0]/self.rate_x
if not rate_y:
rate_y = self.master.height[1]/self.master.height[0]/self.rate_y
# 更新画布的位置及大小数据
self.width[1] *= rate_x
self.height[1] *= rate_y
temp_x, self.rate_x = self.rate_x, self.width[1]/self.width[0]
temp_y, self.rate_y = self.rate_y, self.height[1]/self.height[0]
place_info = self.place_info()
tkinter.Canvas.place( # 更新画布的位置及大小
self,
width=self.width[1]*S,
height=self.height[1]*S,
x=float(place_info['x'])*rate_x,
y=float(place_info['y'])*rate_y)
for widget in self._widget: # 更新子画布控件的子虚拟画布控件位置数据
widget.x1 *= rate_x
widget.x2 *= rate_x
widget.y1 *= rate_y
widget.y2 *= rate_y
for item in self.find_all(): # item 位置缩放
self.coords(
item, *[c*(rate_x, rate_y)[i & 1] for i, c in enumerate(self.coords(item))])
for item in self._font: # 字体大小缩放
self._font[item][1] *= math.sqrt(rate_x*rate_y)
font = self._font[item][:]
font[1] = int(font[1])
self.itemconfigure(item, font=font)
for item in self._image: # 图像大小缩放(采用相对的绝对缩放)
if self._image[item][0] and self._image[item][0].extension != 'gif':
self._image[item][1] = self._image[item][0].zoom(
temp_x*rate_x, temp_y*rate_y, 1.2)
self.itemconfigure(item, image=self._image[item][1])
def __touch(self: Self, event: tkinter.Event, flag: bool = True) -> None:
""" 鼠标触碰控件事件 """
if self._lock:
for widget in self._widget[::-1]:
if widget.live and widget.touch(event) and flag:
if isinstance(widget, CanvasButton):
self.configure(cursor='hand2')
elif isinstance(widget, _TextWidget):
self.configure(cursor='xterm')
else:
self.configure(cursor='arrow')
flag = False
if flag:
self.configure(cursor='arrow')
def __press(self: Self, event: tkinter.Event) -> None:
""" 鼠标左键按下事件 """
if self._lock:
for widget in self._widget[::-1]:
if widget.live and isinstance(widget, CanvasButton | _TextWidget):
widget.press(event) # NOTE: 无需 return,按下空白区域也有作用
def __release(self: Self, event: tkinter.Event) -> None:
""" 鼠标左键松开事件 """
if self._lock:
for widget in self._widget[::-1]:
if widget.live and isinstance(widget, CanvasButton):
if widget.touch(event):
return widget.execute(event)
def __mousewheel(self: Self, event: tkinter.Event) -> None:
""" 鼠标滚轮滚动事件 """
if self._lock:
for widget in self._widget[::-1]:
if widget.live and isinstance(widget, CanvasText):
if widget.scroll(event):
return
def create_text(self: Self, *args, **kw):
# 重写:添加对 text 类型的 _CanvasItemId 的字体大小的控制
font = kw.get('font')
if not font:
kw['font'] = FONT
elif type(font) == str:
kw['font'] = (font, FONT[1])
args = tuple(i*S for i in args)
item = tkinter.Canvas.create_text(self, *args, **kw)
self._font[item] = list(kw['font'])
return item
def create_image(self: Self, *args, **kw):
# 重写:添加对 image 类型的 _CanvasItemId 的图像大小的控制
args = tuple(i*S for i in args)
item = tkinter.Canvas.create_image(self, *args, **kw)
self._image[item] = [kw.get('image'), None]
return item
def create_rectangle(self: Self, *args, **kw):
# 重写:兼容不同缩放的DPI
args = tuple(i*S for i in args)
return tkinter.Canvas.create_rectangle(self, *args, **kw)
def create_line(self: Self, *args, **kw):
# 重写:兼容不同缩放的DPI
args = tuple(i*S for i in args)
return tkinter.Canvas.create_line(self, *args, **kw)
def create_oval(self: Self, *args, **kw):
# 重写:兼容不同缩放的DPI
args = tuple(i*S for i in args)
return tkinter.Canvas.create_oval(self, *args, **kw)
def create_arc(self: Self, *args, **kw):
# 重写:兼容不同缩放的DPI
args = tuple(i*S for i in args)
return tkinter.Canvas.create_arc(self, *args, **kw)
def create_polygon(self: Self, *args, **kw):
# 重写:兼容不同缩放的DPI
args = tuple(i*S for i in args)
return tkinter.Canvas.create_polygon(self, *args, **kw)
def itemconfigure(
self: Self,
tagOrId, # type: str | tkinter._CanvasItemId
**kw
) -> dict[str, tuple[str, str, str, str, str]] | None:
# 重写:创建空image的_CanvasItemId时漏去对图像大小的控制
if type(kw.get('image')) == PhotoImage:
self._image[tagOrId] = [kw.get('image'), None]
return tkinter.Canvas.itemconfigure(self, tagOrId, **kw)
def coords(
self: Self,
__tagOrId, # type: str | tkinter._CanvasItemId
*args
) -> list[float] | None:
# 重写: 兼容不同的DPI缩放
if not args:
return [i/S for i in tkinter.Canvas.coords(self, __tagOrId)]
tkinter.Canvas.coords(self, __tagOrId, *tuple(i*S for i in args))
def move(
self: Self,
tagOrId, # type: str | tkinter._CanvasItemId
x: float,
y: float
) -> None:
# 重写:兼容不同的DPI缩放
return tkinter.Canvas.move(self, tagOrId, x*S, y*S)
def moveto(
self: Self,
tagOrId, # type: str | tkinter._CanvasItemId
x: float | Literal[''],
y: float | Literal['']
) -> None:
# 重写:兼容不同的DPI缩放
return tkinter.Canvas.moveto(self, tagOrId, x*S if x else x, y*S if y else y)
def bbox(
self: Self,
*args # type: str | tkinter._CanvasItemId
) -> tuple[int, int, int, int]:
# 重写:兼容不同的DPI缩放
return tuple(i/S for i in tkinter.Canvas.bbox(self, *args))
def place(self: Self, *args, **kw) -> None:
# 重写:增加一些特定功能并兼容不同的DPI缩放
self.width[0] = kw.get('wdith', self.width[0])
self.height[0] = kw.get('height', self.height[0])
kw.update({key: kw[key]*S for key in kw if key in 'xywidtheight'})
return tkinter.Canvas.place(self, *args, **kw)
def destroy(self: Self) -> None:
# 重写:兼容
self.master._canvas.remove(self)
for widget in self.widget():
widget.destroy()
return tkinter.Canvas.destroy(self)
class _BaseWidget:
""" 虚拟画布控件基类 """
def __init__(
self: Self,
canvas: Canvas,
x: float,
y: float,
width: float,
height: float,
radius: float,
text: str,
justify: str,
borderwidth: float,
font: tuple[str, int, str],
color_text: tuple[str, str, str],
color_fill: tuple[str, str, str],
color_outline: tuple[str, str, str]
) -> None:
"""
### 标准参数
`canvas`: 父画布容器控件
`x`: 控件左上角的横坐标
`y`: 控件左上角的纵坐标
`width`: 控件的宽度
`height`: 控件的高度
`radius`: 控件圆角化半径
`text`: 控件显示的文本,对于文本控件而言,可以为一个元组:(默认文本, 鼠标触碰文本)
`justify`: 文本的对齐方式
`borderwidth`: 外框的宽度
`font`: 控件的字体设定 (字体, 大小, 样式)
`color_text`: 控件文本的颜色
`color_fill`: 控件内部的颜色
`color_outline`: 控件外框的颜色
### 特定参数
`command`: 按钮控件的关联函数
`show`: 文本控件的显示文本
`limit`: 文本控件的输入字数限制,为负数时表示没有字数限制
`read`: 文本控件的只读模式
`cursor`: 输入提示符的字符,默认为一竖线
### 详细说明
字体的值为一个包含两个或三个值的元组,共两种形式
形式一: `(字体名称, 字体大小)`
形式二: `(字体名称, 字体大小, 字体样式)`
颜色为一个包含三个或四个 RGB 颜色字符串的元组,共两种形式
不使用禁用功能时: `(正常颜色, 触碰颜色, 交互颜色)`
需使用禁用功能时: `(正常颜色, 触碰颜色, 交互颜色, 禁用颜色)`
"""
self.master = canvas
self.value = text
self.justify = justify
self.font = font
self.color_text = list(color_text)
self.color_fill = list(color_fill)
self.color_outline = list(color_outline)
self.x1, self.y1 = x, y # 控件左上角坐标
self.x2, self.y2 = x+width, y+height # 控件左下角坐标
self.width, self.height = width, height # 控件的宽高值
self.radius = radius # 边角圆弧半径
self.live = True # 控件活跃标志
self._state = 'normal' # 控件的状态
self.pre_state = None # 记录之前的状态
self.command_ex = {
'normal': None, 'touch': None,
'press': None, 'disabled': None
} # type: dict[str, function | None]
canvas._widget.append(self) # 将实例添加到父画布控件
if radius:
if 2 * radius > width:
radius = width // 2
self.radius = radius
if 2 * radius > height:
radius = height // 2
self.radius = radius
d = 2*radius # 圆角直径
_x, _y, _w, _h = x+radius, y+radius, width-d, height-d
kw = {'outline': '', 'fill': color_fill[0]}
self.inside = [ # 虚拟控件内部填充颜色
canvas.create_rectangle(
x, _y, x+width, y+height-radius, **kw),
canvas.create_rectangle(
_x, y, x+width-radius, y+height, **kw),
canvas.create_arc(
x, y, x+d, y+d, start=90, **kw),
canvas.create_arc(
x+_w, y, x+width, y+d, start=0, **kw),
canvas.create_arc(
x, y+_h, x+d, y+height, start=180, **kw),
canvas.create_arc(
x+_w, y+_h, x+width, y+height, start=270, **kw)]
kw = {'extent': 100, 'style': 'arc', 'outline': color_outline[0]}
self.outside = [ # 虚拟控件外框
canvas.create_line(
_x, y, x+width-radius, y, fill=color_outline[0], width=borderwidth),
canvas.create_line(
_x, y+height, x+width-radius, y+height, fill=color_outline[0], width=borderwidth),
canvas.create_line(
x, _y, x, y+height-radius, fill=color_outline[0], width=borderwidth),
canvas.create_line(
x+width, _y, x+width, y+height-radius+1, fill=color_outline[0], width=borderwidth),
canvas.create_arc(
x, y, x+d, y+d, start=90, width=borderwidth, **kw),
canvas.create_arc(
x+_w, y, x+width, y+d, start=0, width=borderwidth, **kw),
canvas.create_arc(
x, y+_h, x+d, y+height, start=180, width=borderwidth, **kw),
canvas.create_arc(
x+_w, y+_h, x+width, y+height, start=270, width=borderwidth, **kw)]
else:
self.rect = canvas.create_rectangle( # 虚拟控件的外框
x, y, x+width, y+height,
width=borderwidth,
outline=color_outline[0],
fill=color_fill[0])
self.text = canvas.create_text( # 虚拟控件显示的文字
x + (radius+2 if justify == 'left' else width-radius-3
if justify == 'right' else width / 2),
y + height / 2,
text=text,
font=font,
justify=justify,
anchor='w' if justify == 'left' else 'e' if justify == 'right' else 'center',
fill=color_text[0])
def state(self: Self, mode: Literal['normal', 'touch', 'press', 'disabled'] | None = None) -> None:
"""
mode 参数为 None 时仅更新控件,否则改变虚拟控件的外观
`normal`: 正常状态
`touch`: 鼠标触碰时的状态
`press`: 鼠标按下时的状态
`disabled`: 禁用状态
"""
if mode:
self._state, self.pre_state = mode, self._state
if self._state == self.pre_state: # 保持状态时直接跳过
return
if self._state == 'normal':
mode = 0
elif self._state == 'touch':
mode = 1
elif self._state == 'press':
mode = 2
else:
mode = 3
self.master.itemconfigure(self.text, fill=self.color_text[mode])
if isinstance(self, CanvasText):
self.master.itemconfigure(self._text, fill=self.color_text[mode])
if self.radius:
for item in self.inside: # 修改色块
self.master.itemconfigure(item, fill=self.color_fill[mode])
# 修改线条
for item in self.outside[:4]:
self.master.itemconfigure(item, fill=self.color_outline[mode])
for item in self.outside[4:]:
self.master.itemconfigure(
item, outline=self.color_outline[mode])
else:
self.master.itemconfigure(
self.rect, outline=self.color_outline[mode])
if isinstance(self, ProcessBar):
self.master.itemconfigure(self.bottom, fill=self.color_fill[0])
self.master.itemconfigure(self.bar, fill=self.color_fill[1])
else:
self.master.itemconfigure(
self.rect, fill=self.color_fill[mode])
if self.command_ex[self._state]:
self.command_ex[self._state]()
def move(self: Self, dx: float, dy: float) -> None:
"""
移动控件的位置
`dx`: 横向移动长度(单位:像素)
`dy`: 纵向移动长度
"""
self.x1 += dx
self.x2 += dx
self.y1 += dy
self.y2 += dy
if self.radius:
for item in self.inside+self.outside:
self.master.move(item, dx, dy)
else:
self.master.move(self.rect, dx, dy)
self.master.move(self.text, dx, dy)
if isinstance(self, _TextWidget):
self.master.move(self._cursor, dx, dy)
if isinstance(self, CanvasText):
self.master.move(self._text, dx, dy)
if isinstance(self, ProcessBar):
self.master.move(self.bar, dx, dy)
def moveto(self: Self, x: float, y: float) -> None:
"""
改变控件的位置
`x`: 改变到的横坐标(单位:像素)
`y`: 改变到的纵坐标
"""
self.x1, self.x2 = x, x+self.width
self.y1, self.y2 = y, y+self.height
if self.radius:
for item in self.inside+self.outside:
self.master.moveto(item, x, y)
else:
self.master.moveto(self.rect, x, y)
self.master.moveto(self.text, x, y)
if isinstance(self, _TextWidget):
self.master.moveto(self._cursor, x, y)
if isinstance(self, CanvasText):
self.master.moveto(self._text, x, y)
if isinstance(self, ProcessBar):
self.master.moveto(self.bar, x, y)
def configure(self: Self, *args, **kw) -> str | tuple | None:
"""
修改或查询原有参数的值,可供修改或查询的参数有
1. 所有控件: `color_text`、`color_fill`、`color_outline`
2. 非文本控件: `text`
"""
if args:
if args[0] == 'text':
return self.value
else:
return getattr(self, args[0])
value = kw.get('text', None)
text = kw.get('color_text', None)
fill = kw.get('color_fill', None)
outline = kw.get('color_outline', None)
if value:
self.value = value
if text:
self.color_text = text
if fill:
self.color_fill = fill
if outline:
self.color_outline = outline
if isinstance(self, CanvasLabel | CanvasButton | ProcessBar) and value:
self.master.itemconfigure(self.text, text=value)
def destroy(self: Self) -> None:
""" 摧毁控件释放内存 """
self.live = False
self.master._widget.remove(self)
if self.radius:
for item in self.inside+self.outside:
self.master.delete(item)
else:
self.master.delete(self.rect)
if isinstance(self, _TextWidget):
self.master.delete(self._cursor)
if isinstance(self, CanvasText):
self.master.delete(self._text)
if isinstance(self, ProcessBar):
self.master.delete(self.bar)
self.master.delete(self.text)
def set_live(self: Self, boolean: bool | None = None) -> bool | None:
""" 设定或查询live值 """
if boolean == None:
return self.live
else:
self.live = boolean
if boolean:
self.state('normal')
else:
self.state('disabled')
class CanvasLabel(_BaseWidget):
""" 创建一个虚拟的标签控件,用于显示少量文本 """
def __init__(
self: Self,
canvas: Canvas,
x: int,
y: int,
width: int,
height: int,
radius: float = RADIUS,
text: str = '',
borderwidth: int = BORDERWIDTH,
justify: str = tkinter.CENTER,
font: tuple[str, int, str] = FONT,
color_text: tuple[str, str, str] = COLOR_TEXT,
color_fill: tuple[str, str, str] = COLOR_BUTTON_FILL,
color_outline: tuple[str, str, str] = COLOR_BUTTON_OUTLINE
) -> None:
_BaseWidget.__init__(self, canvas, x, y, width, height, radius, text, justify,
borderwidth, font, color_text, color_fill, color_outline)
def touch(self: Self, event: tkinter.Event) -> bool:
""" 触碰状态检测 """
condition = self.x1 <= event.x/S <= self.x2 and self.y1 <= event.y/S <= self.y2
self.state('touch' if condition else 'normal')
return condition
class CanvasButton(_BaseWidget):
""" 创建一个虚拟的按钮,并执行关联函数 """
def __init__(
self: Self,
canvas: Canvas,
x: int,
y: int,
width: int,
height: int,
radius: float = RADIUS,
text: str = '',
borderwidth: int = BORDERWIDTH,
justify: str = tkinter.CENTER,
font: tuple[str, int, str] = FONT,
command=None, # type: function | None
color_text: tuple[str, str, str] = COLOR_TEXT,
color_fill: tuple[str, str, str] = COLOR_BUTTON_FILL,
color_outline: tuple[str, str, str] = COLOR_BUTTON_OUTLINE
) -> None:
_BaseWidget.__init__(self, canvas, x, y, width, height, radius, text, justify,
borderwidth, font, color_text, color_fill, color_outline)
self.command = command
def execute(self: Self, event: tkinter.Event) -> None:
""" 执行关联函数 """
condition = self.x1 <= event.x/S <= self.x2 and self.y1 <= event.y/S <= self.y2
if condition and self.command:
self.command()
def press(self: Self, event: tkinter.Event) -> None:
""" 交互状态检测 """
if self.x1 <= event.x/S <= self.x2 and self.y1 <= event.y/S <= self.y2:
self.state('press')
else:
self.state('normal')
def touch(self: Self, event: tkinter.Event) -> bool:
""" 触碰状态检测 """
condition = self.x1 <= event.x/S <= self.x2 and self.y1 <= event.y/S <= self.y2
self.state('touch' if condition else 'normal')
return condition
class _TextWidget(_BaseWidget):
""" 文本类控件基类 """
def __init__(
self: Self,
canvas: Canvas,
x: int,
y: int,
width: int,
height: int,
radius: float,
text: tuple[str] | str,
limit: int,
justify: str,
icursor: str,
borderwidth: int,
font: tuple[str, int, str],
color_text: tuple[str, str, str],
color_fill: tuple[str, str, str],
color_outline: tuple[str, str, str]
) -> None:
self.limit = limit
self.icursor = icursor
self.interval = 300 # 光标闪烁间
self.flag = False # 光标闪烁标志
# 隐式值
self._value = ['', text, ''] if type(text) == str else ['', *text]
_BaseWidget.__init__(self, canvas, x, y, width, height, radius, '', justify,
borderwidth, font, color_text, color_fill, color_outline)
# 提示光标 NOTE:位置顺序不可乱动
self._cursor = canvas.create_text(0, 0, font=font, fill=color_text[2])
def touch_on(self: Self) -> None:
""" 鼠标悬停状态 """
if self._state != 'press':
self.state('touch')
if self.master.itemcget(self.text, 'text') == self._value[1]:
self.master.itemconfigure(self.text, text=self._value[2])
def touch_off(self: Self) -> None:
""" 鼠标离开状态 """
if self._state != 'press':
self.state('normal')
if self.master.itemcget(self.text, 'text') == self._value[2]:
self.master.itemconfigure(self.text, text=self._value[1])
def press(self: Self, event: tkinter.Event) -> None:
""" 交互状态检测 """
if self.x1 <= event.x/S <= self.x2 and self.y1 <= event.y/S <= self.y2:
if self._state != 'press':
self.press_on()
else:
self.press_off()
def touch(
self, # type: CanvasEntry | CanvasText
event: tkinter.Event
) -> bool:
""" 触碰状态检测 """
condition = self.x1 <= event.x/S <= self.x2 and self.y1 <= event.y/S <= self.y2
self.touch_on() if condition else self.touch_off()
return condition
def cursor_flash(self: Self) -> None:
""" 鼠标光标闪烁 """
if self.interval >= 300:
self.interval, self.flag = 0, not self.flag
if self.flag:
self.master.itemconfigure(self._cursor, text=self.icursor)
else:
self.master.itemconfigure(self._cursor, text='')
if self._state == 'press':
self.interval += 10
self.master.after(10, self.cursor_flash)
else:
self.interval, self.flag = 300, False # 恢复默认值
self.master.itemconfigure(self._cursor, text='')
def cursor_update(self: Self, text: str = ' ') -> None:
""" 鼠标光标更新 """
self.interval, self.flag = 300, False # 恢复默认值
if isinstance(self, CanvasEntry):
self.master.coords(self._cursor, self.master.bbox(
self.text)[2], self.y1+self.height * self.master.rate_y / 2)
elif isinstance(self, CanvasText):
_pos = self.master.bbox(self._text)
self.master.coords(self._cursor, _pos[2], _pos[1])
self.master.itemconfigure(
self._cursor, text='' if not text else self.icursor)
def update(self: Self) -> None:
""" 更新文本显示 """
self.master.itemconfigure(self.text, text=self._value[0])
def paste(self: Self) -> bool:
""" 快捷键粘贴 """
condition = self._state == 'press' and not getattr(self, 'show', None)
if condition:
self.append(self.master.clipboard_get())
return condition
def get(self: Self) -> str:
""" 获取输入框的值 """
return self.value
def set(self: Self, value: str) -> None:
""" 设置输入框的值 """
self.value = self._value[0] = ''
self.append(value)
def append(self: Self, value: str) -> None:
""" 添加输入框的值 """
temp, self._state = self._state, 'press'
event = tkinter.Event()
event.keysym = None
for char in value:
event.char = char
self.input(event)
self._state = temp
class CanvasEntry(_TextWidget):
""" 创建一个虚拟的输入框控件,可输入单行少量字符,并获取这些字符 """
def __init__(
self: Self,
canvas: Canvas,
x: int,
y: int,
width: int,
height: int,
radius: float = RADIUS,
text: tuple[str] | str = '',
show: str | None = None,
limit: int = LIMIT,
cursor: str = CURSOR,
borderwidth: int = BORDERWIDTH,
justify: str = tkinter.LEFT,
font: tuple[str, int, str] = FONT,
color_text: tuple[str, str, str] = COLOR_TEXT,
color_fill: tuple[str, str, str] = COLOR_TEXT_FILL,
color_outline: tuple[str, str, str] = COLOR_TEXT_OUTLINE
) -> None:
_TextWidget.__init__(self, canvas, x, y, width, height, radius, text, limit, justify,
cursor, borderwidth, font, color_text, color_fill, color_outline)
self.master.itemconfigure(self.text, text=self._value[1])
self.show = show
def press_on(self: Self) -> None:
""" 控件获得焦点 """
self.state('press')
self.master.itemconfigure(self.text, text=self._value[0])
self.cursor_update('')
self.cursor_flash()
def press_off(self: Self) -> None:
""" 控件失去焦点 """
self.state('normal')
if self.value == '':
self.master.itemconfigure(self.text, text=self._value[1])