-
Notifications
You must be signed in to change notification settings - Fork 4
/
TinUI.py
3605 lines (3485 loc) · 164 KB
/
TinUI.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
'''
<TinUI, a modern frame to render various widgets elements for tkinter in one control.>
Copyright (C) <2021-present> <smart-space>
'''
from tkinter import *
from webbrowser import open as webopen
import time
import math
import asyncio
import threading
from typing import Union
from types import FunctionType,BuiltinFunctionType
import xml.etree.ElementTree as ET
import sys
import os
import shutil
'''全部组件都是绘制的~~~,除了输入型组件无法使用tkinter画布完成对应效果'''
#==========
'''开发信息
开发者:Smart-Space(Junming Zhang)
版权:版权所有(C) 2019(原型框架,TinGroup子项目)|2021(正式命名TinUI)- present Smart-Space(Junming Zhang)
开发者邮箱:smart-space@qq.com
语言:Python
技术基础:tkinter(tcl/tk)
开源平台:pypi、GitHub、csdn
开源协议:GPLv3
贡献者:(暂无)
免费条款:注明TinUI的开发者,修改后必须开源本文件,且同样使用GPL协议。商业软件需要为TinUI提供开源许可,并声明开发者版权所有
'''
class TinUINum:#数据载体,作者学习阶段的历史遗留产物
pass
class FuncList(list):#控件的函数列表类
def __init__(self,num:int=10):
list.__init__(self)
for i in range(0,num+1):
self.append(None)
class TinUIString(str):#TinUI字符串类
def __init__(self,string:str=''):
str.__init__(self)
self.text=string
class TinUITheme:
'''
专门为特有样式的TinUI或BasicTinUI提供的类
适用于重写样式配色的TinUI或BasicTinUI
该类允许重写样式的TinUI或BasicTinUI使用TinUIXml
'''
def __init__(self,ui,name='tinui-theme'):
self.theme=name
self.ui=ui
self.bbox=ui.bbox
def change_theme_name(self,name:str):
self.theme=name
def get_theme(self):
return self.theme
#弃用,将在不久后删除
class TinUIPen:
'''自绘引擎(试用)目前仅作为记录'''
def __init__(self,canvas):
self.canvas=canvas
def oval(self,x,y,w,h,resolution=32,**kw):
points = [x, y,
x+w, y,
x+w, y+h,
x, y+h,
x, y]
return self.canvas.create_polygon(points, **kw, smooth=True, splinesteps=resolution)
class TinUIFont:
#添加字体文件,参考CustomTkinter
linux_font_path = "~/.fonts/"
@classmethod
def init_font_manager(cls):
# Linux
if sys.platform.startswith("linux"):
try:
if not os.path.isdir(os.path.expanduser(cls.linux_font_path)):
os.mkdir(os.path.expanduser(cls.linux_font_path))
return True
except Exception as err:
sys.stderr.write("FontManager error: " + str(err) + "\n")
return False
# other platforms
else:
return True
@classmethod
def windows_load_font(cls, font_path: Union[str, bytes], private: bool = True, enumerable: bool = False) -> bool:
""" Function taken from: https://stackoverflow.com/questions/11993290/truly-custom-font-in-tkinter/30631309#30631309 """
from ctypes import windll, byref, create_unicode_buffer, create_string_buffer
FR_PRIVATE = 0x10
FR_NOT_ENUM = 0x20
if isinstance(font_path, bytes):
path_buffer = create_string_buffer(font_path)
add_font_resource_ex = windll.gdi32.AddFontResourceExA
elif isinstance(font_path, str):
path_buffer = create_unicode_buffer(font_path)
add_font_resource_ex = windll.gdi32.AddFontResourceExW
else:
raise TypeError('font_path must be of type bytes or str')
flags = (FR_PRIVATE if private else 0) | (FR_NOT_ENUM if not enumerable else 0)
num_fonts_added = add_font_resource_ex(byref(path_buffer), flags, 0)
return bool(min(num_fonts_added, 1))
@classmethod
def load_font(cls, font_path: str) -> bool:
# Windows
if sys.platform.startswith("win"):
return cls.windows_load_font(font_path, private=True, enumerable=False)
# Linux
elif sys.platform.startswith("linux"):
try:
shutil.copy(font_path, os.path.expanduser(cls.linux_font_path))
return True
except Exception as err:
sys.stderr.write("FontManager error: " + str(err) + "\n")
return False
# macOS and others
else:
return False
class TinUIEvent:
'''BasicTinUI与TinUI控件元素事件管理器testing...
可以综合管理每一个画布中所有元素绑定事件的函数
'''
def __init__(self,ui):
self.ui=ui
self.uiddict=dict()#{uid:{event:func,...},...}
def go_func(self,uid,eventname,*event):
#运行一个元素对应事件的所有函数
for func in self.uiddict[uid][eventname]:
func(event)
def bind(self,uid,*event_func):
#每一个新绑定的事件,首次绑定操作,可以同时绑定多个一一对应的事件和函数
#event_func: (event1,func1),(event2,func2)...
self.uiddict[uid]=dict()
for i in event_func:
self.uiddict[uid][i[0]]=[(i[1])]
self.ui.tag_bind(uid,i[0],lambda event,uid=uid,name=i[0]:self.go_func(uid,name,event))
def newbind(self,uid,event_name,func):#新增同事件函数
self.uiddict[uid][eventname].append(func)
def cancelbind(self,uid,eventname,func):#删除同事件函数
self.uiddict[uid][eventname].remove(func)
class BasicTinUI(Canvas):
"""基于tkinter的高级窗口绘制组件
uid参数为每一个组件(除个别)的整体tag_name"""
def __init__(self,master,**kw):
Canvas.__init__(self,master,selectborderwidth=0,highlightthickness=0,bd=0, **kw)
#self.bind('<Button-1>',lambda event:self.focus_set())
self.init()
def init(self):
self.images=[]
self.title_size={0:20,1:18,2:16,3:14,4:12}
self.pen=TinUIPen(self)
self.windows=[]#浮出控件的子窗口,需要开发者手动释放
# @functools.cached_property
# def __get_ratios(self):#获取缩放比例
# return tuple(i/j for i, j in zip(self._size, self._initial_size))
def __get_text_size(self,text):
#获取文本元素字体大小
font=self.itemcget(text,'font').split(' ')
if len(font)==1:
return ''
else:
return ' '+font[1]
def __get_center(self,bbox):#获取中心位置
return (bbox[0]+bbox[2])/2,(bbox[1]+bbox[3])/2
def __auto_anchor(self,uid,pos,anchor='nw'):#统一对齐方式
bbox=self.bbox(uid)
xcenter,ycenter=self.__get_center(bbox)
if anchor=='nw':
dx=pos[0]-bbox[0]
dy=pos[1]-bbox[1]
elif anchor=='n':
dx=pos[0]-xcenter
dy=pos[1]-bbox[1]
elif anchor=='ne':
dx=pos[0]-bbox[2]
dy=pos[1]-bbox[1]
elif anchor=='e':
dx=pos[0]-bbox[2]
dy=pos[1]-ycenter
elif anchor=='se':
dx=pos[0]-bbox[2]
dy=pos[1]-bbox[3]
elif anchor=='s':
dx=pos[0]-xcenter
dy=pos[1]-bbox[3]
elif anchor=='sw':
dx=pos[0]-bbox[0]
dy=pos[1]-bbox[3]
elif anchor=='w':
dx=pos[0]-bbox[0]
dy=pos[1]-ycenter
elif anchor=='center':
dx=pos[0]-xcenter
dy=pos[1]-ycenter
self.move(uid,dx,dy)
return dx,dy
def clean_windows(self):
#清除浮出控件子窗口
for i in self.windows:
try:
i.destroy()
except:
continue
self.windows=[]
#print(self.windows)
def add_title(self,pos:tuple,text:str,fg='black',font='微软雅黑',size=1,anchor='nw',**kw):#绘制标题
kw['anchor']=anchor
return self.create_text(pos,text=text,fill=fg,font=(font,self.title_size[size]),**kw)
def add_paragraph(self,pos:tuple,text:str,fg='black',font=('微软雅黑',12),side='left',width=500,anchor='nw',**kw):#绘制段落
kw['anchor']=anchor
return self.create_text(pos,text=text,fill=fg,font=font,justify=side,width=width,**kw)
def add_button(self,pos:tuple,text:str,fg='#000000',bg='#CCCCCC',line='#CCCCCC',linew='3',activefg='black',activebg='#999999',activeline='#7a7a7a',font=('微软雅黑',12),command=None,anchor='nw'):#绘制按钮
def in_button(event):
self.itemconfig(back,fill=activebg,outline=activeline)
self.itemconfig(button,fill=activefg)
def out_button(event):
self.itemconfig(back,fill=bg,outline=line)
self.itemconfig(button,fill=fg)
def on_click(event):
self.itemconfig(back,fill=activebg,outline=activebg)
self.itemconfig(button,fill=activefg)
self.after(500,lambda : out_button(None))
if command!=None:
command(event)
def change_command(new_func):
nonlocal command
command=new_func
def disable(fg='#7a7a7a',bg='#cccccc'):
self.itemconfig(button,state='disable',fill=fg)
self.itemconfig(back,state='disable',disabledfill=bg)
def active():
self.itemconfig(button,state='normal')
self.itemconfig(back,state='normal')
out_button(None)
button=self.create_text(pos,text=text,fill=fg,font=font,anchor='nw')
uid='button'+str(button)
self.itemconfig(button,tags=uid)
bbox=self.bbox(button)
x1,y1,x2,y2=bbox[0]-3,bbox[1]-3,bbox[2]+3,bbox[3]+3
back=self.create_rectangle((x1,y1,x2,y2),fill=bg,outline=line,width=linew,tags=uid)
self.tag_bind(button,'<Button-1>',on_click)
self.tag_bind(button,'<Enter>',in_button)
self.tag_bind(button,'<Leave>',out_button)
self.tag_bind(back,'<Button-1>',on_click)
self.tag_bind(back,'<Enter>',in_button)
self.tag_bind(back,'<Leave>',out_button)
self.tkraise(button)
self.__auto_anchor(uid,pos,anchor)
funcs=FuncList(3)
funcs.change_command=funcs[0]=change_command
funcs.disable=funcs[1]=disable
funcs.active=funcs[2]=active
return button,back,funcs,uid
def add_label(self,pos:tuple,text:str,fg='black',bg='#f0f0f0',outline='grey',font=('微软雅黑',12),anchor='nw'):#绘制标签
label=self.create_text(pos,text=text,fill=fg,font=font,anchor='nw')
uid='label'+str(label)
self.itemconfig(label,tags=uid)
bbox=self.bbox(label)
x1,y1,x2,y2=bbox[0]-3,bbox[1]-3,bbox[2]+3,bbox[3]+3
back=self.create_rectangle((x1,y1,x2,y2),fill=bg,outline=outline,tags=uid)
self.tkraise(label)
self.__auto_anchor(uid,pos,anchor)
return label,uid
def add_checkbutton(self,pos:tuple,text:str,fontfg='black',fg='#868686',bg='#ededed',activefg='#868686',activebg='#e5e5e5',onfg='white',onbg='#334ac0',font=('微软雅黑',12),command=None,anchor='nw'):#绘制复选框
def button_in(event):
if self.itemcget(check,'fill')==onbg:
pass
else:
self.itemconfig(check,fill=activebg)
self.itemconfig(outl,fill=activefg)
def button_out(event):
if self.itemcget(check,'fill')==onbg:
pass
else:
self.itemconfig(check,fill=bg)
self.itemconfig(outl,fill=fg)
def go_func(event):
if self.itemcget(check,'fill')!=onbg:
self.itemconfig(check,fill=onbg)
self.itemconfig(outl,fill=onfg)
self.itemconfig(state,state='normal')
else:
self.itemconfig(check,fill=bg)
self.itemconfig(outl,fill=fg)
self.itemconfig(state,state='hidden')
if command!=None:
command(event)
def flash():
go_func(None)
def on():
self.itemconfig(check,fill=bg)
go_func(None)
def off():
self.itemconfig(check,fill=onbg)
go_func(None)
def disable():
self.itemconfig(checkbutton,state='disable',fill='#7a7a7a')
self.itemconfig(checkname,state='disable')
def active():
self.itemconfig(checkbutton,state='normal',fill=fontfg)
self.itemconfig(checkname,state='normal')
checkbutton=self.create_text(pos,text=text,fill=fontfg,font=font,anchor='nw')
uid='checkbutton'+str(checkbutton)
self.itemconfig(checkbutton,tags=uid)
bbox=self.bbox(checkbutton)
dic=bbox[3]-bbox[1]#位移长度
midy=pos[1]+dic/2#中间高度坐标
midx=pos[0]+dic/2#中间宽度坐标
font_size=str(int(self.__get_text_size(checkbutton))+2)#字体大小
self.move(checkbutton,dic+5,0)
checkname=uid+'checkname'
outl=self.create_text((midx,midy),text='\uE739',anchor='center',font='{Segoe Fluent Icons} '+font_size,fill=fg,tags=(uid,checkname))#外围边框
check=self.create_text((midx,midy),text='\uE73B',anchor='center',font='{Segoe Fluent Icons} '+font_size,fill=bg,tags=(uid,checkname))#标识符内部元素
state=self.create_text((midx,midy),text='\uE73E',anchor='center',font='{Segoe Fluent Icons} '+font_size,fill=onfg,state='hidden',tags=(uid,checkname))#勾选标识符
self.tkraise(state)
self.tag_bind(checkname,'<Enter>',button_in)
self.tag_bind(checkname,'<Leave>',button_out)
self.tag_bind(checkname,'<Button>',go_func)
self.tag_bind(checkbutton,'<Enter>',button_in)
self.tag_bind(checkbutton,'<Leave>',button_out)
self.tag_bind(checkbutton,'<Button>',go_func)
self.__auto_anchor(uid,pos,anchor)
funcs=FuncList(5)
funcs.flash=funcs[0]=flash
funcs.on=funcs[1]=on
funcs.off=funcs[2]=off
funcs.disable=funcs[3]=disable
funcs.active=funcs[4]=active
return checkbutton,check,funcs,uid
def add_entry(self,pos:tuple,width:int,text:str='',fg='#606060',bg='#f6f6f6',activefg='black',activebg='white',insert='#808080',font=('微软雅黑',12),linew=3,outline='#868686',onoutline='#3041d8',icon='>',anchor='nw',call='→',command=None):#绘制单行输入框
#这是一个半绘制组件
def if_empty(event):
ch=entry.get()
if ch=='':
self.tag_unbind(funcw,'<Leave>')
self.tag_unbind(funcw,'<Enter>')
self.tag_unbind(funcw,'<Button-1>')
self.itemconfig(funcw,text=icon,fill=fg)
else:
if self.itemcget(funcw,'text')==icon:
self.itemconfig(funcw,text='×')
self.tag_bind(funcw,'<Enter>',lambda event:self.itemconfig(funcw,fill=onoutline))
self.tag_bind(funcw,'<Leave>',lambda event:self.itemconfig(funcw,fill=fg))
self.tag_bind(funcw,'<Button-1>',lambda event:(entry.delete(0,'end'),if_empty(None)))
def call_command(event):
text=entry.get()
command(text)
#---
def get_entry():#获取文本
return entry.get()
def __error(errorline='#c42b1c'):#错误样式
self.itemconfig(back,outline=errorline,fill=errorline)
def __normal():#正常样式
entry['state']='normal'
entry.focus_set()
self.itemconfig(back,outline=onoutline,fill=onoutline)
def __disable():#禁用
entry['state']='disable'
self.itemconfig(back,outline=outline,fill=outline)
entry=Entry(self,fg=fg,bg=bg,font=font,relief='flat',bd=0)
entry.insert(0,text)
entry.bind('<KeyRelease>',if_empty)
entry.bind('<FocusIn>',lambda event:(self.itemconfig(back,outline=onoutline),entry.config(background=activebg,foreground=activefg)))
entry.bind('<FocusOut>',lambda event:(self.itemconfig(back,outline=outline),entry.config(background=bg,foreground=fg)))
funce=self.create_window(pos,window=entry,width=width,anchor='nw')#输入框画布对象
uid='entry'+str(funce)
self.itemconfig(funce,tags=uid)
bbox=self.bbox(funce)
funcw=self.create_text((bbox[0]+width,bbox[1]),text=icon,fill=fg,font=font,anchor='nw',tags=uid)
w=self.bbox(funcw)[2]
h=self.bbox(funce)[3]
bubbox=self.bbox(funcw)
if command!=None:#调用函数的绑定仅当存在command时启动
button=self.add_button((w,pos[1]-2),text=call,font=font,command=call_command,fg=fg,bg=bg,linew=0)
self.addtag_withtag(uid,button[-1])
entry.bind('<Return>',call_command)
bubbox=self.bbox(button[-1])
backpos=(bbox[0],bbox[1],bubbox[2],bbox[1],bubbox[2],bbox[3],bbox[0],bbox[3],bbox[0],bbox[1])
outlinepos=(bbox[0]+linew,bbox[3]+4-linew,bubbox[2]-linew,bbox[3]+4-linew)
back=self.create_polygon(outlinepos,fill=outline,outline=outline,width=6+linew,tags=uid)#outline
back1=self.create_polygon(backpos,fill=bg,outline=bg,width=6,tags=uid)#back
if command!=None:
self.tkraise(button[-1])
self.tkraise(funcw)
self.__auto_anchor(uid,pos,anchor)
if_empty(None)
funcs=FuncList(4)
funcs.get=get_entry
funcs.error=__error
funcs.normal=__normal
funcs.disable=__disable
return entry,funcs,uid
def add_separate(self,pos:tuple,width:int,direction='x',fg='grey'):#绘制分割线
def action(x,y):
self.coords(separate,(*pos,x,y))
bbox=list(pos)
separate=self.create_line((*pos,*pos),fill=fg,width=3,capstyle='round')
if direction=='x':
maxl=pos[0]+width
nowl=pos[0]
count=1
for i in range(pos[0],maxl,5):
nowl+=5
self.after(count*5,lambda x=nowl,y=pos[1] :action(x,y))
count+=1
bbox.append(pos[0]+width)
bbox.append(pos[1])
elif direction=='y':
maxl=pos[1]+width
nowl=pos[1]
count=1
for i in range(pos[1],maxl,5):
nowl+=5
self.after(count*5,lambda x=pos[0],y=nowl :action(x,y))
count+=1
bbox.append(pos[0])
bbox.append(pos[1]+width)
self.coords(separate,bbox)
return separate
def add_radiobutton(self,pos:tuple,width,text='',choices=('choose me'),fg='#1a1a1a',bg='#f2f2f2',font=('微软雅黑',12),activefg='#3c3c3c',activebg='#e9e9e9',command=None,anchor='nw'):#绘制单选框
def button_in(tag,t):
self.itemconfig(tag,fill=activebg,outline=activebg)
def button_out(_tag,t):
for tag in back_list:
self.itemconfig(tag,fill=bg,outline=bg)
for t in choices_list:
if t==None or t!=now_choice:
self.itemconfig(t,fill=fg)
def go_func(tag,_text,t):
nonlocal now_choice
now_choice=t
for i in choices_back:#判断是否为当前选中
if i not in back_list:
back_list.append(i)
button_out(tag,t)
back_list.remove(tag)
self.itemconfig(tag,fill=activebg,outline=activebg)
self.itemconfig(t,fill=activefg)
if command!=None:
command(_text)
def select(num):
back=choices_back[num]
_text='select command'
go_func(back,_text,choices_list[num])
def disable():
for f,b in zip(choices_list,choices_back):
self.itemconfig(f,state='disable',fill='#7a7a7a')
self.itemconfig(b,state='disable')
def active():
for f,b in zip(choices_list,choices_back):
self.itemconfig(f,state='normal',fill=fg)
self.itemconfig(b,state='normal')
word=self.create_text(pos,text=text,fill=fg,font=font,anchor='nw',width=width)
now_choice=None#当前选中项
uid='radiobutton'+str(word)
self.itemconfig(word,tags=uid)
start_x=pos[0]#起始x位置
height=self.bbox(word)[3]+3#变量y位置
choices_list=[]
choices_back=[]
for i in choices:
choice=self.create_text((start_x+2,height+2),text=i,fill=fg,font=font,anchor='nw',width=width-4,tags=uid)
bbox=self.bbox(choice)
h=bbox[3]-bbox[1]+4
back=self.create_rectangle((start_x,height,start_x+width,height+h),outline=bg,fill=bg,tags=uid)
self.tkraise(choice)
height+=h+4
choices_list.append(choice)
choices_back.append(back)
self.tag_bind(choice,'<Enter>',lambda event,back=back,c=choice:button_in(back,c))
self.tag_bind(choice,'<Leave>',lambda event,back=back,c=choice:button_out(back,c))
self.tag_bind(back,'<Enter>',lambda event,back=back,c=choice:button_in(back,c))
self.tag_bind(back,'<Leave>',lambda event,back=back,c=choice:button_out(back,c))
self.tag_bind(choice,'<Button>',lambda event,_text=i,back=back,c=choice:go_func(back,_text,c))
self.tag_bind(back,'<Button>',lambda event,_text=i,back=back,c=choice:go_func(back,_text,c))
back_list=list(choices_back)
self.__auto_anchor(uid,pos,anchor)
funcs=FuncList(3)
funcs.select=funcs[0]=select
funcs.disable=funcs[1]=disable
funcs.active=funcs[2]=active
return word,choices_list,choices_back,funcs,uid
def add_link(self,pos:tuple,text,url:Union[str,FunctionType,BuiltinFunctionType],fg='#4f62ca',activefg='red',activebg='#eaeaea',font:tuple=('微软雅黑',12),anchor='nw',command=None):#绘制超链接
def turn_red(event):
self.itemconfig(link,fill=activefg)
self.itemconfig(back,fill=activebg,outline=activebg)
self['cursor']='hand2'
def turn_back(event):
self.itemconfig(link,fill=fg)
self.itemconfig(back,fill='',outline='')
self['cursor']='arrow'
def go_url(event):
#先判断是否含有目标函数,有则只执行目标函数
if command!=None:
command(url)
else:
#url如果是字符串,则打开网页;是方法,则执行函数
if type(url)==str:
webopen(url)
else:
url(event)
def disable(fg='#b0b0b0'):
self.itemconfig(link,state='disable',fill=fg)
self.itemconfig(back,state='disable')
def active():
self.itemconfig(link,state='normal',fill=fg)
self.itemconfig(back,state='normal')
link=self.create_text(pos,text=text,fill=fg,font=font,anchor='nw')
uid='link'+str(link)
self.itemconfig(link,tags=uid)
font=self.itemcget(link,'font')+' underline'
self.itemconfig(link,font=font)
bbox=self.bbox(link)
back=self.create_polygon((bbox[0],bbox[1],bbox[2],bbox[1],bbox[2],bbox[3],bbox[0],bbox[3]),width=7,tags=uid,fill='',outline='')
self.tkraise(link)
self.tag_bind(link,'<Enter>',turn_red)
self.tag_bind(link,'<Leave>',turn_back)
self.tag_bind(link,'<Button-1>',go_url)
self.tag_bind(back,'<Enter>',turn_red)
self.tag_bind(back,'<Leave>',turn_back)
self.tag_bind(back,'<Button-1>',go_url)
if type(url)==str:#为网址,显示提示框
self.add_tooltip(uid,text=url,fg=fg,bg=self['background'],font=font,outline=activebg)
self.__auto_anchor(uid,pos,anchor)
funcs=FuncList(2)
funcs.disable=funcs[0]=disable
funcs.active=funcs[1]=active
return link,funcs,uid
def add_waitbar1(self,pos:tuple,fg='#0078D7',bg='',okfg='lightgreen',okbg='',bd=5,r=20,anchor='nw'):#绘制圆形等待组件
def __start(i):
if ifok.re==True:
return
self.itemconfig(waitbar1,extent=i,start=90+i)
self.update()
if i==355:
start()
def start():
if ifok.re==True:
return
for i in range(0,360,5):
self.after(i*8,lambda i=i:__start(i))
def ok():
ifok.re=True
self.itemconfig(waitbar1,outline=okfg,extent=359)
self.itemconfig(back,fill=okbg)
ifok=TinUINum
ifok.re=False
bbox=(pos[0],pos[1],pos[0]+2*r,pos[1]+2*r)
back_bbox=(pos[0]+bd,pos[1]+bd,pos[0]+2*r-bd,pos[1]+2*r-bd)
back=self.create_oval(back_bbox,width=0,fill=bg)
uid='waitbar1-'+str(back)
self.itemconfig(back,tags=uid)
waitbar1=self.create_arc(bbox,outline=fg,extent=5,start=90,width=bd,style='arc',tags=uid)
self.__auto_anchor(uid,pos,anchor)
start()
return waitbar1,ok,uid
def add_labelframe(self,widgets:tuple=(),title='',font='微软雅黑 10',fg='#A8A8A8',bg='',pos=None):#绘制标题框
sx,sy,ex,ey=self.bbox(widgets[0])#获取直接的起始位置
for i in widgets:
nsx,nsy,nex,ney=self.bbox(i)
sx=nsx if nsx<sx else sx
sy=nsy if nsy<sy else sy
ex=nex if nex>ex else ex
ey=ney if ney>ey else ey
bg=self['background'] if bg=='' else bg
back=self.create_polygon((sx,sy-12,ex,sy-12,ex,ey,sx,ey),fill=bg,outline=bg,width=11)
uid='labelframe-'+str(back)
self.itemconfig(back,tags=uid)
self.lower(back)
outline=self.create_polygon((sx-1,sy-12-1,ex+1,sy-12-1,ex+1,ey+1,sx-1,ey+1),fill=fg,outline=fg,width=11,tags=uid)
self.lower(outline)
label=self.create_text(((sx+ex)//2,sy-20),font=font,text=title,fill=fg,anchor='center',tags=uid)
self.create_rectangle(self.bbox(label),fill=bg,outline=bg,tags=uid)
self.tag_raise(label)
return label,back,outline,uid
def add_waitbar2(self,pos:tuple,width:int=240,fg='#3041d8',bg='#f3f3f3',okcolor='#0f7b0f',anchor='nw'):#绘制点状等待框
#单点运动
def ball_go(ball,w,x,num):
self.move(ball,x,0)
self.update()
if num==4 and w>=width:
for i in balls:
self.coords(i,pos)
self.update()
start()
#单点运动控制
def _start(ball):
if ifok.re==True:
return
self.itemconfig(ball,state='normal')
num=balls.index(ball)
fast=width//2
for w in range(0,width+5-fast,5):
self.after(w*10,lambda w=w:ball_go(ball,w,5,num))
for w in range(width+5-fast,width+5-fast//2,5):
self.after(w*10,lambda w=w:ball_go(ball,w+fast//2,10,num))
#整体动画控制
def start():
if ifok.re==True:
return
for i in balls:
#每0.3秒释放一个小球标识
self.after(balls.index(i)*300,lambda i=i:_start(i))
def stop():
ifok.re=True
for i in balls:
self.itemconfig(i,state='hidden')
self.itemconfig(back,fill=okcolor,width=3)
ifok=TinUINum()
ifok.re=False
bbox=(pos[0],pos[1],pos[0]+width+10,pos[1]+5)
back=self.create_line((pos[0],pos[1]+5,pos[0]+width+5,pos[1]+5),fill=fg,width=1,capstyle='round')
uid='waitbar2-'+str(back)
self.itemconfig(back,tags=uid)
dx,dy=self.__auto_anchor(uid,pos,anchor)
pos=list(pos)
pos[0]+=dx
pos[1]+=dy
balls=[]
ball_bbox=(pos[0],pos[1],pos[0]+5,pos[1]+5)
for b in range(1,6):
ball=self.create_text(pos,text='\uF127',fill=fg,state='hidden',font='{Segoe Fluent Icons} 4',tags=uid)
balls.append(ball)
start()
return back,balls,stop,uid
def add_combobox(self,pos:tuple,width:int=200,height:int=200,text='',content:tuple=(),fg='#1a1a1a',bg='#f8f8f8',outline='#c8c8c8',activefg='#191919',activebg='#f1f1f1',scrollbg='#f0f0f0',scrollcolor='#999999',scrollon='#89898b',tran='#01FF11',font=('微软雅黑',12),anchor='nw',command=None):#绘制组合/下拉框
def open_box(event):
if self.itemcget(button_text,'text')=='∨':
self.itemconfig(button_text,text='∧',fill=activefg)
show(event)
else:
unshow(None)
self.itemconfig(button_text,text='∨',fill=fg)
def readyshow():#计算显示位置
allpos=bar.bbox('all')
#菜单尺寸
winw=allpos[2]-allpos[0]+5
winh=allpos[3]-allpos[1]+5
#屏幕尺寸
maxx=self.winfo_screenwidth()
maxy=self.winfo_screenheight()
wind.data=(maxx,maxy,winw,winh)
def show(event):#显示的起始位置
#初始位置
maxx,maxy,winw,winh=wind.data
bbox=self.bbox(uid)
scx,scy=event.x_root,event.y_root#屏幕坐标
dx,dy=round(self.canvasx(event.x,)-bbox[0]),round(self.canvasy(event.y)-bbox[3])#画布坐标差值
sx,sy=scx-dx,scy-dy
if sx+winw>maxx:
x=sx-winw
else:
x=sx
if sy+winh>maxy:
y=sy-winh
else:
y=sy
pickbox.geometry(f'{winw+15}x{winh+15}+{x-4}+{y}')
pickbox.attributes('-alpha',0)
pickbox.deiconify()
pickbox.focus_set()
for i in [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1]:
pickbox.attributes('-alpha',i)
pickbox.update()
time.sleep(0.05)
pickbox.bind('<FocusOut>',unshow)
def unshow(event):
pickbox.withdraw()
pickbox.unbind('<FocusOut>')
self.itemconfig(button_text,text='∨',fill=fg)
def choose_this(word):
self.itemconfig(main,text=word)
unshow(None)
if command!=None:
command(word)
def select(num):
self.itemconfig(button_text,text='∧',fill=activefg)
choose_this(*info[num])
def disable():
self.itemconfig(button_text,text='∧',fill=activefg)
open_box(None)
button_funcs[1](bg=bg)
def active():
button_funcs[2]()
if activefg=='':
activefg=self['background']
main=self.create_text(pos,text=text,font=font,fill=fg,anchor='nw')
uid='combobox'+str(main)
self.itemconfig(main,tags=uid)
bbox=self.bbox(main)
x1,y1,x2,y2=bbox[0]-3,bbox[1]-3,bbox[0]+width+3,bbox[3]+3
back=self.create_rectangle((x1,y1,x2,y2),fill=bg,outline=fg,tags=uid)
self.tkraise(main)
button_text,button_back,button_funcs,button_id=self.add_button((x2,y1-1),'∨',fg,bg,'#CCCCCC',1,activefg,activebg,'#7a7a7a',font=font,command=open_box)
self.addtag_withtag(uid,button_id)
pickbox=Toplevel(self)
self.windows.append(pickbox)
pickbox.geometry(f'{width}x{height}')
pickbox.overrideredirect(True)
pickbox.attributes('-topmost',1)
pickbox.withdraw()#隐藏窗口
pickbox.attributes('-transparent',tran)
wind=TinUINum()#记录数据
bar=BasicTinUI(pickbox,bg=tran)
bar.pack(fill='both',expand=True)
bar.create_polygon((9,9,width-9,9,width-9,height-9,9,height-9),fill=bg,outline=bg,width=9)
bar.lower(bar.create_polygon((8,8,width-8,8,width-8,height-8,8,height-8),fill=outline,outline=outline,width=9))
bar.add_listbox((8,8),width-38,height-38,bg=bg,fg=fg,data=content,activebg=activebg,sel=activebg,font=font,scrollbg=scrollbg,scrollcolor=scrollcolor,scrollon=scrollon,command=choose_this)
self.__auto_anchor(uid,pos,anchor)
readyshow()
funcs=FuncList(3)
funcs.select=funcs[0]=select
funcs.disable=funcs[1]=disable
funcs.active=funcs[2]=active
return main,back,bar,funcs,uid
def add_progressbar(self,pos:tuple,width=250,fg='#868686',bg='#334ac0',back='#f3f3f3',fontc='#79b8f8',percentage=True,text='',anchor='nw'):#绘制进度条
def goto(num:int):
if not 0<=num<=100:
return
pw=width*num//100
self.coords(progressbar,pos[0],pos[1],pos[0]+pw,pos[1]+15)
if percentage==True:
self.itemconfig(text,text=str(num)+'%')
self.update()
def now_running():
self.itemconfig(text,fill=fontc)
self.itemconfig(back,outline=fg)
self.itemconfig(progressbar,outline=bg,fill=bg)
def now_paused(fg='#868686',bg='#9d5d00',fontc='#cdcdcd'):
self.itemconfig(text,fill=fontc)
self.itemconfig(back,outline=fg)
self.itemconfig(progressbar,outline=bg,fill=bg)
def now_error(fg='#868686',bg='#c42b1c',fontc='#cdcdcd'):
self.itemconfig(text,fill=fontc)
self.itemconfig(back,outline=fg)
self.itemconfig(progressbar,outline=bg,fill=bg)
pos=list(pos)
bbox=(pos[0],pos[1],pos[0]+width,pos[1]+15)
back=self.create_rectangle((bbox),outline=fg,fill=back)
uid='progressbar'+str(back)
self.itemconfig(back,tags=uid)
progressbar=self.create_rectangle((pos[0],pos[1],pos[0],pos[1]+15),outline=bg,fill=bg,tags=uid)
pro_tagname='progressbar>'+str(back)
self.addtag_withtag(progressbar,pro_tagname)
#是否显示默认文本
if percentage==True:
text=self.create_text((pos[0]+width//2,pos[1]),anchor='n',text='0%',fill=fontc,font='微软雅黑 10',tags=uid)
else:
text=self.create_text((pos[0]+width//2,pos[1]),anchor='n',text=text,fill=fontc,font='微软雅黑 10',tags=uid)
dx,dy=self.__auto_anchor(uid,pos,anchor)
pos[0]+=dx
pos[1]+=dy
funcs=FuncList(3)
funcs.now_running=funcs[0]=now_running
funcs.now_paused=funcs[1]=now_paused
funcs.now_error=funcs[2]=now_error
return back,pro_tagname,text,goto,funcs,uid
def add_table(self,pos:tuple,outline='#E1E1E1',fg='black',bg='white',data=[['1','2','3'],['a','b','c']],minwidth=100,maxwidth=300,font=('微软雅黑',12),headbg='#d9ebf9',anchor='nw'):#绘制表格
def get_max_height(widths:dict):
height=0
for i in widths.values():
height=i[1] if i[1]>height else height
#重新绘制
for back in widths.keys():
x1,y1,x2=widths[back][2]
y2=y1+height
self.coords(widths[back][0],x1,y1,x2,y2)
self.tkraise(widths[back][3])
return height
title_num=len(data[0])#获取表头个数
end_x,end_y=pos#起始位置
height,relheight=0,0
line_width={}#获取每列的固定宽度
count=1
ti_list=[]
for i in data[0]:
title=self.create_text((end_x,end_y),anchor='nw',text=i,fill=fg,font=font,width=maxwidth)
if count==1:#只取第一个背景作为tag id
uid='table'+str(title)
self.itemconfig(title,tags=uid)
bbox=self.bbox(title)
if bbox[2]-bbox[0]<=minwidth:
width=minwidth
else:
width=bbox[2]-bbox[0]
line_width[count]=width
height=bbox[3]-bbox[1]
relheight=height if height>relheight else relheight
ti_back=self.create_rectangle((end_x-1,end_y,end_x+width,end_y+height),outline='',fill='',tags=uid)
ti_list.append((ti_back,end_x-1,end_y,end_x+width))
end_x=end_x+width+2
count+=1
self.tkraise(title)
for i in ti_list:#保持表头高度一致
self.coords(i[0],i[1],i[2],i[3],i[2]+relheight)
end_y=pos[1]+relheight+1
v_endx,v_endy=pos[0],end_y+2
for line in data[1:]:
count=1
a_dict={}
end_x=pos[0]
height=0
for a in line:
width=line_width[count]
cont=self.create_text((end_x,end_y),anchor='nw',text=a,fill=fg,width=width,font=font,tags=uid)
bbox=self.bbox(cont)
height=bbox[3]-bbox[1]
back=self.create_rectangle((end_x-1,end_y,end_x+width,end_y+height),outline=bg,fill=bg,tags=uid)
self.tkraise(cont)
a_dict[count]=(back,height,(end_x-1,end_y,end_x+width),cont)#(end_x,end_y,width)为重新绘制确定位置范围
end_x=end_x+width+2
count+=1
height=get_max_height(a_dict)
end_y=end_y+height+1
last_line=self.create_line((pos[0],end_y-1,end_x,end_y-1),fill=outline,tags=uid)
self.delete(last_line)#删除最后一行水平分割线
for i in ti_list[1:]:#竖直分割线
self.create_line((i[1]-1,pos[1],i[1]-1,end_y),fill=outline,tags=uid)
all_back=self.create_polygon((pos[0],pos[1],end_x-1,pos[1],end_x-1,end_y-1,pos[0],end_y-1),width=9,outline=headbg,fill=headbg,tags=uid)
outline_back=self.create_polygon((pos[0]-1,pos[1]-1,end_x,pos[1]-1,end_x,end_y,pos[0]-1,end_y),width=9,outline=outline,fill=outline,tags=uid)
value_back=self.create_polygon((v_endx,v_endy,end_x-1,v_endy,end_x-1,end_y-1,pos[0],end_y-1),width=9,outline=bg,fill=bg,tags=uid)
self.lower(value_back)
self.lower(all_back)
self.lower(outline_back)
self.__auto_anchor(uid,pos,anchor)
return uid
def add_onoff(self,pos:tuple,fg='#575757',bg='#e5e5e5',onfg='#FFFFFF',onbg='#3041d8',anchor='nw',command=None):#绘制开关控件
def __on():
nonlocal nowstate
nowstate='on'
if command!=None:
command(True)
def __off():
nonlocal nowstate
nowstate='off'
if command!=None:
command(False)
def __left30():
f=lambda:self.move(state,-1,0)
for i in range(0,30):
self.after(i*5,f)
def __right30():
f=lambda:self.move(state,1,0)
for i in range(0,30):
self.after(i*5,f)
def __on_click(event):
if nowstate=='off':
self.itemconfig(state,fill=onfg)
__right30()
self.itemconfig(back,fill=onbg)
self.itemconfig(outline,fill=onbg)
__on()
else:
self.itemconfig(state,fill=fg)
__left30()
self.itemconfig(back,fill=bg)
self.itemconfig(outline,fill=fg)
__off()
def on():#开启
if nowstate=='off':
self.itemconfig(state,fill=onfg)
__right30()
self.itemconfig(back,fill=onbg)
self.itemconfig(outline,fill=onbg)
__on()
def off():#关闭
if nowstate=='on':
self.itemconfig(state,fill=fg)
__left30()
self.itemconfig(back,fill=bg)
self.itemconfig(outline,fill=fg)
__off()
def disable(dfg='#f0f0f0',dbg='#bfbfbf'):#禁用
self.itemconfig(uid,state='disable')
self.itemconfig(state,fill=dfg)
self.itemconfig(outline,fill=dbg)
self.itemconfig(back,fill=dbg)
def active():#启用
self.itemconfig(uid,state='normal')
if nowstate=='on':
self.itemconfig(state,fill=onfg)
self.itemconfig(back,fill=onbg)
self.itemconfig(outline,fill=onbg)
else:
self.itemconfig(state,fill=fg)
self.itemconfig(back,fill=bg)
self.itemconfig(outline,fill=fg)
nowstate='off'
back=self.create_text(pos,text='\uEC11',font='{Segoe Fluent Icons} 40',fill=bg,anchor='nw')
uid='onoff'+str(back)
self.itemconfig(back,tags=uid)
outline=self.create_text(pos,text='\uEC12',font='{Segoe Fluent Icons} 40',fill=fg,tags=uid,anchor='nw')
self.__auto_anchor(uid,pos,anchor)
bbox=self.bbox(outline)
state=self.create_text((bbox[0]+13,(bbox[1]+bbox[3])/2-1),text='\uF127',font='{Segoe Fluent Icons} 10',fill=fg,tags=uid,anchor='center')
self.tag_bind(uid,'<Button-1>',__on_click)
funcs=FuncList(4)
funcs.on=on
funcs.off=off
funcs.disable=disable
funcs.active=active
return state,back,outline,funcs,uid
def add_spinbox(self,pos:tuple,width=150,data=('1','2','3'),now='',fg='#1b1b1b',bg='#ffffff',line='#e5e5e5',activefg='#818181',activebg='#f2f2f2',font=('微软雅黑',12),anchor='nw',command=None):#绘制选值框
def updata(event):
val=check_in_data()
if val[0]==True:
datanum.num=data.index(val[1])
index=datanum.num-1
if index<0:
return
datanum.num-=1
wentry.delete(0,'end')
wentry.insert(0,data[index])
if command!=None:
result=TinUIString(data[index])
result.num=index
command(result)
def downdata(event):
val=check_in_data()
if val[0]==True:
datanum.num=data.index(val[1])
index=datanum.num+1
if index>maxnum:
return
datanum.num+=1
wentry.delete(0,'end')
wentry.insert(0,data[index])
if command!=None:
result=TinUIString(data[index])
result.num=index
command(result)
def check_in_data():
val=wentry.get()
if val in data:
return True,val
else:
return False,val
if bg=='':
bg=self['background']
wentry=Entry(self,font=font,fg=fg,highlightthickness=0,insertwidth=1,bd=1,bg=bg,relief='flat')