tkwin11 0.2.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tkwin11/__init__.py +72 -0
- tkwin11/button.py +218 -0
- tkwin11/cards.py +130 -0
- tkwin11/charts.py +578 -0
- tkwin11/classic.py +115 -0
- tkwin11/core.py +1416 -0
- tkwin11/dataview.py +218 -0
- tkwin11/dpi.py +555 -0
- tkwin11/dropdowns.py +169 -0
- tkwin11/expansion.py +89 -0
- tkwin11/extras.py +487 -0
- tkwin11/feedback.py +280 -0
- tkwin11/fluent.py +409 -0
- tkwin11/flyouts.py +128 -0
- tkwin11/forms.py +527 -0
- tkwin11/inputs.py +154 -0
- tkwin11/layouts.py +60 -0
- tkwin11/media.py +412 -0
- tkwin11/menus.py +61 -0
- tkwin11/motion.py +126 -0
- tkwin11/navigation.py +248 -0
- tkwin11/placeholder.py +173 -0
- tkwin11/popups.py +219 -0
- tkwin11/render.py +198 -0
- tkwin11/restore_animation.py +189 -0
- tkwin11/scrolling.py +99 -0
- tkwin11/selection.py +157 -0
- tkwin11/slider.py +460 -0
- tkwin11/states.py +49 -0
- tkwin11/switches.py +284 -0
- tkwin11/table.py +400 -0
- tkwin11/tcl_bridge.py +137 -0
- tkwin11/titlebar.py +59 -0
- tkwin11/tooltip.py +116 -0
- tkwin11/widgets.py +303 -0
- tkwin11/window_chrome.py +801 -0
- tkwin11-0.2.3.dist-info/METADATA +88 -0
- tkwin11-0.2.3.dist-info/RECORD +40 -0
- tkwin11-0.2.3.dist-info/WHEEL +4 -0
- tkwin11-0.2.3.dist-info/licenses/LICENSE +22 -0
tkwin11/charts.py
ADDED
|
@@ -0,0 +1,578 @@
|
|
|
1
|
+
"""Interactive Canvas charts for small Tkinter tools. No third-party dependencies.
|
|
2
|
+
|
|
3
|
+
LineChart, ColumnChart, ScatterChart, DonutChart and PieChart accept Python lists.
|
|
4
|
+
Hover changes only overlay items. Data, view and resize redraws are coalesced.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
import bisect
|
|
8
|
+
import copy
|
|
9
|
+
import math
|
|
10
|
+
import tkinter as tk
|
|
11
|
+
from tkinter import ttk, font as tkfont
|
|
12
|
+
from .core import PALETTE
|
|
13
|
+
from .render import SmoothImage
|
|
14
|
+
from .motion import Tween
|
|
15
|
+
|
|
16
|
+
COLORS = ('#087DFF', '#19A58B', '#E9A13B', '#8B68D9', '#DC708E', '#269DB2')
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _number(value):
|
|
20
|
+
if value is None:return None
|
|
21
|
+
try:value=float(value)
|
|
22
|
+
except (TypeError,ValueError) as error:raise ValueError(f'图表需要数值,收到 {value!r}') from error
|
|
23
|
+
return value if math.isfinite(value) else None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _format(value):
|
|
27
|
+
if value==0:return '0'
|
|
28
|
+
if abs(value)>=1e6 or abs(value)<.001:return f'{value:.3g}'
|
|
29
|
+
return f'{value:,.3f}'.rstrip('0').rstrip('.') if value!=int(value) else f'{value:,.0f}'
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _ticks(low,high,count=5):
|
|
33
|
+
raw=(high-low)/max(1,count-1)
|
|
34
|
+
if not math.isfinite(raw) or raw<=0:return [low]
|
|
35
|
+
power=10**math.floor(math.log10(raw))
|
|
36
|
+
step=next((n*power for n in (1,2,2.5,5,10) if n*power>=raw),10*power)
|
|
37
|
+
first=math.ceil(low/step)*step
|
|
38
|
+
return [0.0 if abs(first+i*step)<step*1e-9 else first+i*step
|
|
39
|
+
for i in range(min(20,max(0,int((high-first)/step)+1)))]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _clip_segment(x1,y1,x2,y2,rect):
|
|
43
|
+
left,top,right,bottom=rect;dx=x2-x1;dy=y2-y1;start,end=0.,1.
|
|
44
|
+
for p,q in ((-dx,x1-left),(dx,right-x1),(-dy,y1-top),(dy,bottom-y1)):
|
|
45
|
+
if p==0:
|
|
46
|
+
if q<0:return None
|
|
47
|
+
else:
|
|
48
|
+
value=q/p
|
|
49
|
+
if p<0:start=max(start,value)
|
|
50
|
+
else:end=min(end,value)
|
|
51
|
+
if start>end:return None
|
|
52
|
+
return x1+start*dx,y1+start*dy,x1+end*dx,y1+end*dy
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class _Chart(ttk.Frame):
|
|
56
|
+
def __init__(self,master,*,height=230,on_click=None,tooltip_formatter=None,**kwargs):
|
|
57
|
+
super().__init__(master,**kwargs)
|
|
58
|
+
self.scale=self.winfo_fpixels('1i')/96;self.px=lambda value:max(1,round(value*self.scale))
|
|
59
|
+
self.on_click=on_click;self.tooltip_formatter=tooltip_formatter
|
|
60
|
+
self._data_tween=Tween(self)
|
|
61
|
+
self.last_selection=None;self.hidden=set();self._closed=False
|
|
62
|
+
self._draw_job=None;self._hover_job=None;self._pointer=None;self._hover=None
|
|
63
|
+
self._highlighted=None;self._drag_start=None;self._previous_grab=None
|
|
64
|
+
self._aa_photo=None;self._marker_images={}
|
|
65
|
+
self.font=tkfont.Font(self,font='TkDefaultFont');self.font.configure(size=max(8,int(self.font.cget('size'))-1))
|
|
66
|
+
self.toolbar=ttk.Frame(self);self.toolbar.pack(fill='x',pady=(0,self.px(4)))
|
|
67
|
+
self.legend=ttk.Frame(self.toolbar);self.legend.pack(side='left',fill='x',expand=True)
|
|
68
|
+
self.legend.bind('<Configure>',self._layout_legend)
|
|
69
|
+
self._legend_labels=[]
|
|
70
|
+
self.canvas=tk.Canvas(self,height=self.px(height),width=self.px(240),background=PALETTE['bg'],
|
|
71
|
+
highlightthickness=0,borderwidth=0,takefocus=True)
|
|
72
|
+
self.canvas._dpi_native_images=True
|
|
73
|
+
self._logical_height=height
|
|
74
|
+
self.canvas.pack(fill='both',expand=True)
|
|
75
|
+
self.canvas.bind('<Configure>',lambda e:self.schedule())
|
|
76
|
+
self._key_index=-1
|
|
77
|
+
for key,delta in [('Left',-1),('Up',-1),('Right',1),('Down',1)]:
|
|
78
|
+
self.canvas.bind('<'+key+'>',lambda e,n=delta:self._key_move(n))
|
|
79
|
+
self.canvas.bind('<Home>',lambda e:self._key_move(0,0))
|
|
80
|
+
self.canvas.bind('<End>',lambda e:self._key_move(0,-1))
|
|
81
|
+
self.canvas.bind('<Return>',self._key_select);self.canvas.bind('<space>',self._key_select)
|
|
82
|
+
self.canvas.bind('<FocusOut>',lambda e:self._clear_hover())
|
|
83
|
+
self.canvas.bind('<Motion>',self._motion)
|
|
84
|
+
self.canvas.bind('<Leave>',lambda e:self._clear_hover())
|
|
85
|
+
self.canvas.bind('<ButtonPress-1>',self._press)
|
|
86
|
+
self.canvas.bind('<ButtonRelease-1>',self._release)
|
|
87
|
+
self.canvas.bind('<B1-Motion>',self._drag)
|
|
88
|
+
self.bind('<Destroy>',self._cleanup,add='+')
|
|
89
|
+
|
|
90
|
+
def _tkwin11_dpi_changed(self,dpi):
|
|
91
|
+
self.scale=dpi/96;self._marker_images.clear()
|
|
92
|
+
self.canvas.configure(height=self.px(self._logical_height))
|
|
93
|
+
self._clear_hover();self.schedule()
|
|
94
|
+
|
|
95
|
+
def _transition_data(self,attribute,target,field):
|
|
96
|
+
old=getattr(self,attribute,[]);self._data_tween.cancel()
|
|
97
|
+
def compatible(a,b):
|
|
98
|
+
if a is None or b is None:return a is b
|
|
99
|
+
if isinstance(a,(list,tuple)) and isinstance(b,(list,tuple)):return len(a)==len(b) and all(compatible(x,y) for x,y in zip(a,b))
|
|
100
|
+
return isinstance(a,(int,float)) and isinstance(b,(int,float))
|
|
101
|
+
count=sum(len(item[field]) if isinstance(item[field],list) else 1 for item in target)
|
|
102
|
+
ok=len(old)==len(target) and count<=1000 and all(a['name']==b['name'] and compatible(a[field],b[field]) for a,b in zip(old,target))
|
|
103
|
+
if not ok:setattr(self,attribute,copy.deepcopy(target));self.schedule();return
|
|
104
|
+
def mix(a,b,t):
|
|
105
|
+
if b is None:return None
|
|
106
|
+
if isinstance(b,(list,tuple)):return [mix(x,y,t) for x,y in zip(a,b)]
|
|
107
|
+
return a+(b-a)*t
|
|
108
|
+
def paint(amount):
|
|
109
|
+
rows=copy.deepcopy(target)
|
|
110
|
+
for row,a,b in zip(rows,old,target):row[field]=mix(a[field],b[field],amount)
|
|
111
|
+
setattr(self,attribute,rows);self.schedule()
|
|
112
|
+
self._data_tween.start(0.,1.,paint,duration=200)
|
|
113
|
+
|
|
114
|
+
def _key_move(self,delta,index=None):
|
|
115
|
+
if self.instate(['disabled']):return 'break'
|
|
116
|
+
hits=getattr(self,'_hits',[]) or [h for _,items in getattr(self,'_line_index',[]) for h in items] or getattr(self,'_slices',[])
|
|
117
|
+
if not hits:return 'break'
|
|
118
|
+
self._key_index=(self._key_index+delta)%len(hits) if index is None else index%len(hits)
|
|
119
|
+
hit=hits[self._key_index]
|
|
120
|
+
x,y=hit.get('x',self.canvas.winfo_width()/2),hit.get('y',self.canvas.winfo_height()/2)
|
|
121
|
+
self._show_hit(hit,x,y)
|
|
122
|
+
return 'break'
|
|
123
|
+
def _key_select(self,event=None):
|
|
124
|
+
if self._hover is not None and not self.instate(['disabled']):self._select_hit(self._hover)
|
|
125
|
+
return 'break'
|
|
126
|
+
def state(self,statespec=None):
|
|
127
|
+
result=super().state(statespec)
|
|
128
|
+
if statespec is not None and hasattr(self,'canvas'):
|
|
129
|
+
disabled=self.instate(['disabled'])
|
|
130
|
+
from .states import descendants_disabled
|
|
131
|
+
if not hasattr(self,'_disabled_children'):self._disabled_children={}
|
|
132
|
+
descendants_disabled(self,disabled,self._disabled_children)
|
|
133
|
+
if disabled:
|
|
134
|
+
self._clear_hover();self._drag_start=None
|
|
135
|
+
if self.canvas.grab_current() is self.canvas:
|
|
136
|
+
self.canvas.grab_release()
|
|
137
|
+
if self._previous_grab is not None and self._previous_grab.winfo_exists():self._previous_grab.grab_set()
|
|
138
|
+
self._previous_grab=None
|
|
139
|
+
for label in self._legend_labels:
|
|
140
|
+
label.configure(takefocus=not disabled,cursor='' if disabled else 'hand2',foreground=PALETTE['disabled'] if disabled or label._series_name in self.hidden else label._series_color)
|
|
141
|
+
return result
|
|
142
|
+
|
|
143
|
+
def _set_legend(self,items):
|
|
144
|
+
for label in self._legend_labels:label.destroy()
|
|
145
|
+
self._legend_labels=[]
|
|
146
|
+
for name,color in items:
|
|
147
|
+
label=tk.Label(self.legend,text='● '+name,font=self.font,padx=self.px(5),pady=self.px(3),
|
|
148
|
+
background=PALETTE['bg'],foreground=PALETTE['muted'] if name in self.hidden else color,
|
|
149
|
+
cursor='hand2',takefocus=True,highlightthickness=1,
|
|
150
|
+
highlightbackground=PALETTE['bg'],highlightcolor=PALETTE['blue'])
|
|
151
|
+
label._series_name=name;label._series_color=color
|
|
152
|
+
label.bind('<Button-1>',lambda e,n=name:self.toggle_series(n))
|
|
153
|
+
label.bind('<space>',lambda e,n=name:self.toggle_series(n))
|
|
154
|
+
label.bind('<Return>',lambda e,n=name:self.toggle_series(n))
|
|
155
|
+
self._legend_labels.append(label)
|
|
156
|
+
self._layout_legend()
|
|
157
|
+
if self.instate(['disabled']):self.state(['disabled'])
|
|
158
|
+
def _layout_legend(self,event=None):
|
|
159
|
+
available=max(self.px(120),self.legend.winfo_width());row=col=used=0
|
|
160
|
+
for label in self._legend_labels:
|
|
161
|
+
width=label.winfo_reqwidth()+self.px(4)
|
|
162
|
+
if used and used+width>available:row+=1;col=used=0
|
|
163
|
+
label.grid(row=row,column=col,sticky='w',padx=(0,self.px(4)))
|
|
164
|
+
col+=1;used+=width
|
|
165
|
+
def toggle_series(self,name):
|
|
166
|
+
if self.instate(['disabled']):return 'break'
|
|
167
|
+
if name not in {label._series_name for label in self._legend_labels}:raise KeyError(name)
|
|
168
|
+
if name in self.hidden:self.hidden.remove(name)
|
|
169
|
+
else:self.hidden.add(name)
|
|
170
|
+
for label in self._legend_labels:
|
|
171
|
+
label.configure(foreground=PALETTE['disabled'] if label._series_name in self.hidden else label._series_color)
|
|
172
|
+
self.schedule();self.event_generate('<<ChartSeriesChanged>>',when='tail')
|
|
173
|
+
return 'break'
|
|
174
|
+
def schedule(self):
|
|
175
|
+
if not self._closed and self._draw_job is None:self._draw_job=self.after(16,self._redraw)
|
|
176
|
+
def redraw(self):
|
|
177
|
+
if self._draw_job is not None:self.after_cancel(self._draw_job);self._draw_job=None
|
|
178
|
+
self._redraw()
|
|
179
|
+
def _redraw(self):
|
|
180
|
+
self._draw_job=None
|
|
181
|
+
if self._closed:return
|
|
182
|
+
self._clear_hover();self.canvas.delete('plot')
|
|
183
|
+
self._draw()
|
|
184
|
+
def _motion(self,event):
|
|
185
|
+
if self.instate(['disabled']):return
|
|
186
|
+
self._pointer=(event.x,event.y)
|
|
187
|
+
if self._hover_job is None:self._hover_job=self.after(16,self._update_hover)
|
|
188
|
+
def _update_hover(self):
|
|
189
|
+
self._hover_job=None
|
|
190
|
+
if self._closed or self.instate(['disabled']) or self._pointer is None:return
|
|
191
|
+
x,y=self._pointer;hit=self._hit(x,y)
|
|
192
|
+
if hit is None:self._clear_hover();return
|
|
193
|
+
self._show_hit(hit,x,y)
|
|
194
|
+
def _show_hit(self,hit,x,y):
|
|
195
|
+
self._clear_hover(cancel_job=False)
|
|
196
|
+
self._hover=hit
|
|
197
|
+
self._draw_highlight(hit)
|
|
198
|
+
if self.tooltip_formatter:text=str(self.tooltip_formatter(dict(hit['data'])))
|
|
199
|
+
else:text=self._tooltip_text(hit['data'])
|
|
200
|
+
# Keep the tooltip in this canvas; no Toplevel, images or global grab.
|
|
201
|
+
text_item=self.canvas.create_text(0,0,text=text,font=self.font,anchor='nw',fill=PALETTE['fg'],
|
|
202
|
+
width=max(self.px(60),self.canvas.winfo_width()-self.px(36)),tags='overlay')
|
|
203
|
+
bounds=self.canvas.bbox(text_item)
|
|
204
|
+
pad=self.px(8);width=bounds[2]-bounds[0]+2*pad;height=bounds[3]-bounds[1]+2*pad
|
|
205
|
+
left=max(2,min(x+self.px(14),self.canvas.winfo_width()-width-2))
|
|
206
|
+
top=max(2,min(y+self.px(16),self.canvas.winfo_height()-height-2))
|
|
207
|
+
box=self.canvas.create_rectangle(left,top,left+width,top+height,fill=PALETTE['bg'],outline='#CCD1DC',tags='overlay')
|
|
208
|
+
self.canvas.coords(text_item,left+pad,top+pad);self.canvas.tag_raise(text_item,box)
|
|
209
|
+
def _clear_hover(self,cancel_job=True):
|
|
210
|
+
if cancel_job and self._hover_job is not None:self.after_cancel(self._hover_job);self._hover_job=None
|
|
211
|
+
if self._highlighted is not None:
|
|
212
|
+
item,color=self._highlighted;self.canvas.itemconfigure(item,fill=color);self._highlighted=None
|
|
213
|
+
self.canvas.delete('overlay');self._hover=None
|
|
214
|
+
def _draw_highlight(self,hit):
|
|
215
|
+
if 'item' in hit:
|
|
216
|
+
item=hit['item'];self._highlighted=(item,hit['color'])
|
|
217
|
+
channels=self.winfo_rgb(hit['color'])
|
|
218
|
+
color='#'+''.join(f'{round(v/257*.84):02x}' for v in channels)
|
|
219
|
+
self.canvas.itemconfigure(item,fill=color)
|
|
220
|
+
def _tooltip_text(self,data):return str(data)
|
|
221
|
+
def _press(self,event):
|
|
222
|
+
if self.instate(['disabled']):return 'break'
|
|
223
|
+
self.canvas.focus_set();self._press_position=(event.x,event.y)
|
|
224
|
+
def _drag(self,event):pass
|
|
225
|
+
def _release(self,event):
|
|
226
|
+
if self.instate(['disabled']):return 'break'
|
|
227
|
+
hit=self._hit(event.x,event.y)
|
|
228
|
+
if hit is not None:self._select_hit(hit)
|
|
229
|
+
def _select_hit(self,hit):
|
|
230
|
+
if self.instate(['disabled']):return 'break'
|
|
231
|
+
self.last_selection=dict(hit['data'])
|
|
232
|
+
if self.on_click:self.on_click(dict(self.last_selection))
|
|
233
|
+
self.event_generate('<<ChartSelected>>',when='tail')
|
|
234
|
+
def _empty(self,text='暂无数据'):
|
|
235
|
+
self.canvas.create_text(self.canvas.winfo_width()/2,self.canvas.winfo_height()/2,
|
|
236
|
+
text=text,font=self.font,fill=PALETTE['muted'],tags='plot')
|
|
237
|
+
def _cleanup(self,event):
|
|
238
|
+
if event.widget is not self:return
|
|
239
|
+
self._closed=True
|
|
240
|
+
for job in (self._draw_job,self._hover_job):
|
|
241
|
+
if job is not None:self.after_cancel(job)
|
|
242
|
+
try:
|
|
243
|
+
if self._previous_grab is not None and self._previous_grab.winfo_exists():self._previous_grab.grab_set()
|
|
244
|
+
except tk.TclError:pass
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
class _CartesianChart(_Chart):
|
|
248
|
+
kind='line'
|
|
249
|
+
def __init__(self,master,*,series=None,values=None,labels=None,height=230,y_formatter=None,x_formatter=None,**kwargs):
|
|
250
|
+
super().__init__(master,height=height,**kwargs)
|
|
251
|
+
self.y_formatter=y_formatter or _format;self.x_formatter=x_formatter or _format
|
|
252
|
+
self.series=[];self.labels=[];self._view=None;self._plot=None
|
|
253
|
+
self._hits=[];self._line_index=[];self._buckets={};self._full_bounds=(0.,1.,0.,1.)
|
|
254
|
+
if self.kind!='bar':
|
|
255
|
+
ttk.Button(self.toolbar,text='重置',style='Quiet.TButton',command=self.reset_view).pack(side='right')
|
|
256
|
+
self.canvas.bind('<MouseWheel>',self._wheel)
|
|
257
|
+
self.canvas.bind('<Double-Button-1>',lambda e:self.reset_view())
|
|
258
|
+
self.canvas.bind('<Escape>',lambda e:self.reset_view())
|
|
259
|
+
self.set_data(series=series,values=values,labels=labels)
|
|
260
|
+
|
|
261
|
+
def set_data(self,series=None,*,values=None,labels=None,reset_view=True):
|
|
262
|
+
if series is not None and values is not None:raise ValueError('请只传 series 或 values 其中之一')
|
|
263
|
+
if series is None:series=[{'name':'数据','values':list(values or [])}]
|
|
264
|
+
parsed=[];names=set()
|
|
265
|
+
for index,item in enumerate(series):
|
|
266
|
+
name=str(item.get('name',f'系列 {index+1}'))
|
|
267
|
+
if name in names:raise ValueError('系列名称不能重复:'+name)
|
|
268
|
+
names.add(name)
|
|
269
|
+
color=item.get('color',PALETTE['accent'] if index==0 else COLORS[index%len(COLORS)])
|
|
270
|
+
self.winfo_rgb(color)
|
|
271
|
+
if 'points' in item:
|
|
272
|
+
if self.kind=='bar':raise ValueError('柱状图使用 values 和 labels,而不是 points')
|
|
273
|
+
points=[]
|
|
274
|
+
for point in item['points']:
|
|
275
|
+
if point is None:points.append(None);continue
|
|
276
|
+
if len(point)!=2:raise ValueError('points 中每个点都应是 (x, y)')
|
|
277
|
+
x,y=map(_number,point);points.append(None if x is None or y is None else (x,y))
|
|
278
|
+
else:points=[None if (y:=_number(value)) is None else (float(i),y) for i,value in enumerate(item.get('values',[]))]
|
|
279
|
+
parsed.append({'name':name,'color':color,'points':points})
|
|
280
|
+
self.series=parsed
|
|
281
|
+
self._transition_data('_visual_series',parsed,'points')
|
|
282
|
+
if labels is not None:self.labels=[str(value) for value in labels]
|
|
283
|
+
self.hidden.intersection_update(names)
|
|
284
|
+
if reset_view:self._view=None
|
|
285
|
+
self._set_legend([(item['name'],item['color']) for item in self.series])
|
|
286
|
+
self.schedule()
|
|
287
|
+
def get_data(self):
|
|
288
|
+
if self.kind=='bar':
|
|
289
|
+
return [{'name':series['name'],'color':series['color'],
|
|
290
|
+
'values':[point[1] if point is not None else None for point in series['points']]} for series in self.series]
|
|
291
|
+
return copy.deepcopy(self.series)
|
|
292
|
+
def _bounds(self):
|
|
293
|
+
points=[point for series in self.series if series['name'] not in self.hidden for point in series['points'] if point is not None]
|
|
294
|
+
if not points:return None
|
|
295
|
+
xs,ys=zip(*points);xmin,xmax=min(xs),max(xs);ymin,ymax=min(ys),max(ys)
|
|
296
|
+
if self.kind=='bar':
|
|
297
|
+
xmin=-.5;xmax=max(len(series['points']) for series in self.series)-.5
|
|
298
|
+
ymin=min(0,ymin);ymax=max(0,ymax)
|
|
299
|
+
else:
|
|
300
|
+
xpad=(xmax-xmin)*.03 if xmax>xmin else max(1,abs(xmin)*.1)
|
|
301
|
+
xmin-=xpad;xmax+=xpad
|
|
302
|
+
ypad=(ymax-ymin)*.08 if ymax>ymin else max(1,abs(ymin)*.1)
|
|
303
|
+
return xmin,xmax,ymin-ypad,ymax+ypad
|
|
304
|
+
def _draw(self):
|
|
305
|
+
self._hits=[];self._line_index=[];self._buckets={}
|
|
306
|
+
bounds=self._bounds()
|
|
307
|
+
if bounds is None:
|
|
308
|
+
self._plot=None;self._empty('点击图例显示数据' if self.hidden else '暂无数据');return
|
|
309
|
+
self._full_bounds=bounds
|
|
310
|
+
if self._view is None:view=bounds
|
|
311
|
+
else:view=self._clamp_view(self._view);self._view=view
|
|
312
|
+
self._draw_bounds=view
|
|
313
|
+
xmin,xmax,ymin,ymax=view
|
|
314
|
+
yticks=_ticks(ymin,ymax)
|
|
315
|
+
left=max(self.px(42),max((self.font.measure(str(self.y_formatter(y))) for y in yticks),default=0)+self.px(10))
|
|
316
|
+
right=self.canvas.winfo_width()-self.px(12);top=self.px(12);bottom=self.canvas.winfo_height()-self.px(32)
|
|
317
|
+
if right-left<self.px(35) or bottom-top<self.px(35):self._plot=None;return
|
|
318
|
+
self._plot=(left,top,right,bottom)
|
|
319
|
+
for y in yticks:
|
|
320
|
+
sy=self._xy(xmin,y)[1]
|
|
321
|
+
self.canvas.create_line(left,sy,right,sy,fill=PALETTE['border'],dash=(2,4),tags='plot')
|
|
322
|
+
self.canvas.create_text(left-self.px(8),sy,text=self.y_formatter(y),anchor='e',font=self.font,fill=PALETTE['muted'],tags='plot')
|
|
323
|
+
if self.labels:
|
|
324
|
+
first=max(0,math.ceil(xmin));last=min(len(self.labels)-1,math.floor(xmax))
|
|
325
|
+
capacity=max(1,int((right-left)/self.px(64)));step=max(1,math.ceil((last-first+1)/capacity))
|
|
326
|
+
xticks=list(range(first,last+1,step))
|
|
327
|
+
else:xticks=_ticks(xmin,xmax,max(2,int((right-left)/self.px(80))))
|
|
328
|
+
for x in xticks:
|
|
329
|
+
sx=self._xy(x,ymin)[0]
|
|
330
|
+
label=self.labels[int(x)] if self.labels and int(x)==x and 0<=int(x)<len(self.labels) else str(self.x_formatter(x))
|
|
331
|
+
while self.font.measure(label)>self.px(85) and len(label)>3:label=label[:-2]+'…'
|
|
332
|
+
self.canvas.create_text(sx,bottom+self.px(16),text=label,font=self.font,fill=PALETTE['muted'],tags='plot')
|
|
333
|
+
self.canvas.create_line(left,bottom,right,bottom,fill=PALETTE['border'],tags='plot')
|
|
334
|
+
if ymin<0<ymax:
|
|
335
|
+
sy=self._xy(xmin,0)[1];self.canvas.create_line(left,sy,right,sy,fill='#BFC7D3',tags='plot')
|
|
336
|
+
visible=[item for item in self._visual_series if item['name'] not in self.hidden]
|
|
337
|
+
if self.kind=='bar':
|
|
338
|
+
for series_index,series in enumerate(visible):self._draw_bars(series,series_index,len(visible))
|
|
339
|
+
else:
|
|
340
|
+
with SmoothImage(self,self.canvas.winfo_width(),self.canvas.winfo_height()) as surface:
|
|
341
|
+
self._smooth=surface
|
|
342
|
+
for series in visible:self._draw_points(series)
|
|
343
|
+
self._aa_photo=surface.photo()
|
|
344
|
+
self._smooth=None
|
|
345
|
+
self.canvas.create_image(0,0,image=self._aa_photo,anchor='nw',tags='plot')
|
|
346
|
+
def _xy(self,x,y):
|
|
347
|
+
left,top,right,bottom=self._plot;xmin,xmax,ymin,ymax=self._draw_bounds
|
|
348
|
+
return left+(x-xmin)/(xmax-xmin)*(right-left),bottom-(y-ymin)/(ymax-ymin)*(bottom-top)
|
|
349
|
+
def _data_at(self,x,y):
|
|
350
|
+
left,top,right,bottom=self._plot;xmin,xmax,ymin,ymax=self._draw_bounds
|
|
351
|
+
return xmin+(x-left)/(right-left)*(xmax-xmin),ymax-(y-top)/(bottom-top)*(ymax-ymin)
|
|
352
|
+
def _payload(self,series,index,point):
|
|
353
|
+
logical=next((item for item in self.series if item['name']==series['name']),series)
|
|
354
|
+
point=logical['points'][index] or point
|
|
355
|
+
x,y=point
|
|
356
|
+
label=self.labels[int(x)] if int(x)==x and 0<=int(x)<len(self.labels) else str(self.x_formatter(x))
|
|
357
|
+
return {'series':series['name'],'index':index,'x':x,'y':y,'label':label,'kind':self.kind}
|
|
358
|
+
def _draw_points(self,series):
|
|
359
|
+
color=series['color'];last=None;path=[];lookup=[]
|
|
360
|
+
left,top,right,bottom=self._plot
|
|
361
|
+
show_markers=self.kind=='scatter' or len(series['points'])<=60
|
|
362
|
+
def flush():
|
|
363
|
+
if len(path)>=4:self._smooth.line(path,color,width=self.px(2))
|
|
364
|
+
path.clear()
|
|
365
|
+
for index,point in enumerate(series['points']):
|
|
366
|
+
if point is None:flush();last=None;continue
|
|
367
|
+
x,y=self._xy(*point)
|
|
368
|
+
if self.kind=='line' and last is not None:
|
|
369
|
+
clipped=_clip_segment(*last,x,y,self._plot)
|
|
370
|
+
if clipped:
|
|
371
|
+
if path and (abs(path[-2]-clipped[0])>1e-6 or abs(path[-1]-clipped[1])>1e-6):flush()
|
|
372
|
+
if not path:path.extend(clipped[:2])
|
|
373
|
+
path.extend(clipped[2:])
|
|
374
|
+
else:flush()
|
|
375
|
+
last=(x,y)
|
|
376
|
+
if not (left<=x<=right and top<=y<=bottom):continue
|
|
377
|
+
hit={'x':x,'y':y,'color':color,'data':self._payload(series,index,point)}
|
|
378
|
+
lookup.append(hit)
|
|
379
|
+
if show_markers:
|
|
380
|
+
radius=self.px(3 if self.kind=='line' else 3.5)
|
|
381
|
+
self._smooth.ellipse((x-radius,y-radius,x+radius,y+radius),fill=color,outline=PALETTE['bg'],width=1)
|
|
382
|
+
if self.kind=='scatter':
|
|
383
|
+
key=(int(x//self.px(24)),int(y//self.px(24)))
|
|
384
|
+
self._buckets.setdefault(key,[]).append(hit)
|
|
385
|
+
flush()
|
|
386
|
+
lookup.sort(key=lambda hit:hit['x'])
|
|
387
|
+
self._line_index.append(([hit['x'] for hit in lookup],lookup))
|
|
388
|
+
def _draw_bars(self,series,index,count):
|
|
389
|
+
left,top,right,bottom=self._plot
|
|
390
|
+
zero=self._xy(0,0)[1];slot=(right-left)/(self._draw_bounds[1]-self._draw_bounds[0])
|
|
391
|
+
group_width=slot*.72;bar_width=max(1,group_width/count-self.px(2))
|
|
392
|
+
for i,point in enumerate(series['points']):
|
|
393
|
+
if point is None:continue
|
|
394
|
+
x,y=self._xy(*point);x=x-group_width/2+index*group_width/count
|
|
395
|
+
y1=max(top,min(y,zero));y2=min(bottom,max(y,zero))
|
|
396
|
+
if y2-y1<1:y2=y1+1
|
|
397
|
+
item=self.canvas.create_rectangle(x,y1,x+bar_width,y2,fill=series['color'],outline='',tags='plot')
|
|
398
|
+
self._hits.append({'bbox':(x,y1,x+bar_width,y2),'x':x+bar_width/2,'y':y,
|
|
399
|
+
'item':item,'color':series['color'],'data':self._payload(series,i,point)})
|
|
400
|
+
def _inside(self,x,y):
|
|
401
|
+
return self._plot is not None and self._plot[0]<=x<=self._plot[2] and self._plot[1]<=y<=self._plot[3]
|
|
402
|
+
def _hit(self,x,y):
|
|
403
|
+
if not self._inside(x,y):return None
|
|
404
|
+
if self.kind=='bar':
|
|
405
|
+
return next((hit for hit in self._hits if hit['bbox'][0]<=x<=hit['bbox'][2] and hit['bbox'][1]-2<=y<=hit['bbox'][3]+2),None)
|
|
406
|
+
if self.kind=='scatter':
|
|
407
|
+
col,row=int(x//self.px(24)),int(y//self.px(24))
|
|
408
|
+
hits=[hit for dx in (-1,0,1) for dy in (-1,0,1) for hit in self._buckets.get((col+dx,row+dy),[])]
|
|
409
|
+
hit=min(hits,key=lambda h:(h['x']-x)**2+(h['y']-y)**2,default=None)
|
|
410
|
+
return hit if hit and math.hypot(hit['x']-x,hit['y']-y)<=self.px(14) else None
|
|
411
|
+
candidates=[]
|
|
412
|
+
for xs,hits in self._line_index:
|
|
413
|
+
index=bisect.bisect_left(xs,x)
|
|
414
|
+
candidates.extend(hits[i] for i in (index-1,index) if 0<=i<len(hits))
|
|
415
|
+
return min(candidates,key=lambda h:(abs(h['x']-x),abs(h['y']-y)),default=None)
|
|
416
|
+
def _draw_highlight(self,hit):
|
|
417
|
+
if self.kind=='bar':super()._draw_highlight(hit);return
|
|
418
|
+
left,top,right,bottom=self._plot;x,y=hit['x'],hit['y'];radius=self.px(5)
|
|
419
|
+
self.canvas.create_line(x,top,x,bottom,fill='#A9B4C4',dash=(3,3),tags='overlay')
|
|
420
|
+
self.canvas.create_line(left,y,right,y,fill='#CDD3DE',dash=(3,3),tags='overlay')
|
|
421
|
+
key=(hit['color'],radius)
|
|
422
|
+
if key not in self._marker_images:
|
|
423
|
+
size=2*radius+self.px(6);center=size/2
|
|
424
|
+
with SmoothImage(self,size,size) as surface:
|
|
425
|
+
surface.ellipse((center-radius,center-radius,center+radius,center+radius),fill=PALETTE['bg'],outline=hit['color'],width=self.px(2))
|
|
426
|
+
self._marker_images[key]=surface.photo()
|
|
427
|
+
self.canvas.create_image(x,y,image=self._marker_images[key],tags='overlay')
|
|
428
|
+
def _tooltip_text(self,data):
|
|
429
|
+
return f"{data['series']}\n{data['label']} · {self.y_formatter(data['y'])}"
|
|
430
|
+
def reset_view(self):
|
|
431
|
+
if self.instate(['disabled']):return 'break'
|
|
432
|
+
self._view=None;self.schedule();self.event_generate('<<ChartViewChanged>>',when='tail');return 'break'
|
|
433
|
+
def _clamp_view(self,view):
|
|
434
|
+
full=self._full_bounds;result=[]
|
|
435
|
+
for low,high,base_low,base_high in ((view[0],view[1],full[0],full[1]),(view[2],view[3],full[2],full[3])):
|
|
436
|
+
span=min(high-low,base_high-base_low)
|
|
437
|
+
low=max(base_low,min(low,base_high-span));result.extend((low,low+span))
|
|
438
|
+
return tuple(result)
|
|
439
|
+
def _wheel(self,event):
|
|
440
|
+
if self.instate(['disabled']):return 'break'
|
|
441
|
+
if not self._inside(event.x,event.y) or not event.delta:return
|
|
442
|
+
old=self._view or self._full_bounds;center=self._data_at(event.x,event.y)
|
|
443
|
+
factor=.82 if event.delta>0 else 1/.82
|
|
444
|
+
# Lines zoom horizontally by default; Shift zooms y. Scatter zooms both.
|
|
445
|
+
axes=(False,True) if event.state&1 else ((True,True) if self.kind=='scatter' else (True,False))
|
|
446
|
+
new=[]
|
|
447
|
+
for axis,(low,high) in enumerate(((old[0],old[1]),(old[2],old[3]))):
|
|
448
|
+
if axes[axis]:
|
|
449
|
+
span=(high-low)*factor;fullspan=self._full_bounds[axis*2+1]-self._full_bounds[axis*2]
|
|
450
|
+
span=max(fullspan/10000,min(span,fullspan));ratio=(center[axis]-low)/(high-low)
|
|
451
|
+
low=center[axis]-span*ratio;high=low+span
|
|
452
|
+
new.extend((low,high))
|
|
453
|
+
self._view=self._clamp_view(tuple(new));self.schedule();self.event_generate('<<ChartViewChanged>>',when='tail')
|
|
454
|
+
return 'break'
|
|
455
|
+
def _press(self,event):
|
|
456
|
+
if self.instate(['disabled']):return 'break'
|
|
457
|
+
super()._press(event)
|
|
458
|
+
if self.kind!='bar' and self._inside(event.x,event.y):
|
|
459
|
+
self._drag_start=(event.x,event.y,self._view or self._full_bounds)
|
|
460
|
+
self._previous_grab=self.canvas.grab_current();self.canvas.grab_set()
|
|
461
|
+
def _drag(self,event):
|
|
462
|
+
if self.instate(['disabled']):return 'break'
|
|
463
|
+
if self._drag_start is None:return
|
|
464
|
+
x,y,view=self._drag_start;left,top,right,bottom=self._plot
|
|
465
|
+
dx=(event.x-x)/(right-left)*(view[1]-view[0]);dy=(event.y-y)/(bottom-top)*(view[3]-view[2])
|
|
466
|
+
self._view=self._clamp_view((view[0]-dx,view[1]-dx,view[2]+dy,view[3]+dy))
|
|
467
|
+
self.schedule();return 'break'
|
|
468
|
+
def _release(self,event):
|
|
469
|
+
if self.instate(['disabled']):return 'break'
|
|
470
|
+
origin=getattr(self,'_press_position',(event.x,event.y));moved=math.hypot(event.x-origin[0],event.y-origin[1])>self.px(4)
|
|
471
|
+
self._drag_start=None
|
|
472
|
+
if self.canvas.grab_current() is self.canvas:
|
|
473
|
+
self.canvas.grab_release()
|
|
474
|
+
if self._previous_grab is not None and self._previous_grab.winfo_exists():self._previous_grab.grab_set()
|
|
475
|
+
self._previous_grab=None
|
|
476
|
+
if not moved:super()._release(event)
|
|
477
|
+
else:self.event_generate('<<ChartViewChanged>>',when='tail')
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
class LineChart(_CartesianChart):
|
|
481
|
+
"""Line chart with gaps, multiple series, crosshair, zoom and pan."""
|
|
482
|
+
kind='line'
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
class ColumnChart(_CartesianChart):
|
|
486
|
+
"""Grouped vertical bars, including negative values and multiple series."""
|
|
487
|
+
kind='bar'
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
class ScatterChart(_CartesianChart):
|
|
491
|
+
"""Scatter plot with bucket-indexed hit testing, zoom and pan."""
|
|
492
|
+
kind='scatter'
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
class DonutChart(_Chart):
|
|
496
|
+
def __init__(self,master,*,data=None,hole=.62,height=230,value_formatter=None,**kwargs):
|
|
497
|
+
super().__init__(master,height=height,**kwargs)
|
|
498
|
+
if not 0<=hole<=.85:raise ValueError('hole 应在 0 到 0.85 之间')
|
|
499
|
+
self.hole=hole;self.value_formatter=value_formatter or _format
|
|
500
|
+
self.data=[];self._slices=[];self._center=None;self._aa_item=None;self._lit_slice=None
|
|
501
|
+
self.set_data(data or [])
|
|
502
|
+
def set_hole(self,hole):
|
|
503
|
+
if not 0<=hole<=.85:raise ValueError('hole 应在 0 到 0.85 之间')
|
|
504
|
+
self.hole=hole;self.schedule()
|
|
505
|
+
def set_data(self,data):
|
|
506
|
+
parsed=[];names=set()
|
|
507
|
+
for index,item in enumerate(data):
|
|
508
|
+
if isinstance(item,dict):name=item['name'];value=item['value'];color=item.get('color',COLORS[index%len(COLORS)])
|
|
509
|
+
else:name,value=item;color=COLORS[index%len(COLORS)]
|
|
510
|
+
name=str(name);value=_number(value)
|
|
511
|
+
if value is None or value<0:raise ValueError('饼图 / 环形图需要有限的非负数值')
|
|
512
|
+
if name in names:raise ValueError('名称不能重复:'+name)
|
|
513
|
+
names.add(name);self.winfo_rgb(color)
|
|
514
|
+
parsed.append({'name':name,'value':value,'color':color})
|
|
515
|
+
self.data=parsed;self._transition_data('_visual_data',parsed,'value');self.hidden.intersection_update(names)
|
|
516
|
+
self._set_legend([(item['name'],item['color']) for item in parsed]);self.schedule()
|
|
517
|
+
def get_data(self):return copy.deepcopy(self.data)
|
|
518
|
+
def _draw(self):
|
|
519
|
+
self._slices=[];self._center=None
|
|
520
|
+
items=[item for item in self._visual_data if item['name'] not in self.hidden and item['value']>0]
|
|
521
|
+
total=sum(item['value'] for item in items)
|
|
522
|
+
if not total:self._empty('点击图例显示数据' if self.hidden else '暂无数据');return
|
|
523
|
+
width,height=self.canvas.winfo_width(),self.canvas.winfo_height()
|
|
524
|
+
radius=max(1,min(width,height)/2-self.px(12));cx=width/2;cy=height/2
|
|
525
|
+
self._center=(cx,cy,radius);bounds=(cx-radius,cy-radius,cx+radius,cy+radius)
|
|
526
|
+
angle=0.
|
|
527
|
+
for item in items:
|
|
528
|
+
extent=item['value']/total*360
|
|
529
|
+
logical=next(row for row in self.data if row['name']==item['name'])
|
|
530
|
+
logical_total=sum(row['value'] for row in self.data if row['name'] not in self.hidden)
|
|
531
|
+
self._slices.append({'start':angle,'end':angle+extent,'color':item['color'],
|
|
532
|
+
'data':{'name':item['name'],'value':logical['value'],'percent':logical['value']/logical_total*100 if logical_total else 0,'kind':'donut' if self.hole else 'pie'}})
|
|
533
|
+
angle+=extent
|
|
534
|
+
self._paint_slices()
|
|
535
|
+
if self.hole:
|
|
536
|
+
inner=radius*self.hole
|
|
537
|
+
text=str(self.value_formatter(total))
|
|
538
|
+
self.canvas.create_text(cx,cy-self.px(7),text=text,font=(self.font.actual('family'),self.font.actual('size')+4,'bold'),fill=PALETTE['fg'],tags='plot')
|
|
539
|
+
self.canvas.create_text(cx,cy+self.px(17),text='合计',font=self.font,fill=PALETTE['muted'],tags='plot')
|
|
540
|
+
def _paint_slices(self,highlight=None):
|
|
541
|
+
if not self._slices or self._center is None:return
|
|
542
|
+
cx,cy,radius=self._center;pad=self.px(3);size=math.ceil(2*(radius+pad));center=size/2
|
|
543
|
+
bounds=(center-radius,center-radius,center+radius,center+radius)
|
|
544
|
+
with SmoothImage(self,size,size) as surface:
|
|
545
|
+
for item in self._slices:
|
|
546
|
+
color=item['color']
|
|
547
|
+
if item['data']['name']==highlight:color='#'+''.join(f'{round(v/257*.84):02x}' for v in self.winfo_rgb(color))
|
|
548
|
+
surface.pie(bounds,item['start']-90,item['end']-item['start'],color)
|
|
549
|
+
if len(self._slices)>1:
|
|
550
|
+
for item in self._slices:
|
|
551
|
+
angle=math.radians(item['start']-90)
|
|
552
|
+
surface.line([center,center,center+radius*math.cos(angle),center+radius*math.sin(angle)],PALETTE['bg'],self.px(2))
|
|
553
|
+
if self.hole:
|
|
554
|
+
inner=radius*self.hole;surface.ellipse((center-inner,center-inner,center+inner,center+inner),fill=PALETTE['bg'])
|
|
555
|
+
self._aa_photo=surface.photo()
|
|
556
|
+
if self._aa_item is not None and self.canvas.type(self._aa_item)=='image':
|
|
557
|
+
self.canvas.itemconfigure(self._aa_item,image=self._aa_photo);self.canvas.coords(self._aa_item,cx,cy)
|
|
558
|
+
else:self._aa_item=self.canvas.create_image(cx,cy,image=self._aa_photo,tags='plot')
|
|
559
|
+
self.canvas.tag_lower(self._aa_item)
|
|
560
|
+
def _draw_highlight(self,hit):
|
|
561
|
+
self._lit_slice=hit['data']['name'];self._paint_slices(self._lit_slice)
|
|
562
|
+
def _clear_hover(self,cancel_job=True):
|
|
563
|
+
if getattr(self,'_lit_slice',None) is not None:
|
|
564
|
+
self._lit_slice=None;self._paint_slices()
|
|
565
|
+
super()._clear_hover(cancel_job)
|
|
566
|
+
def _hit(self,x,y):
|
|
567
|
+
if self._center is None:return None
|
|
568
|
+
cx,cy,radius=self._center;distance=math.hypot(x-cx,y-cy)
|
|
569
|
+
if not radius*self.hole<=distance<=radius:return None
|
|
570
|
+
angle=(90-math.degrees(math.atan2(cy-y,x-cx)))%360
|
|
571
|
+
return next((item for item in self._slices if item['start']<=angle<item['end']),None)
|
|
572
|
+
def _tooltip_text(self,data):return f"{data['name']}\n{self.value_formatter(data['value'])} · {data['percent']:.1f}%"
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
class PieChart(DonutChart):
|
|
576
|
+
def __init__(self,master,**kwargs):
|
|
577
|
+
kwargs.setdefault('hole',0)
|
|
578
|
+
super().__init__(master,**kwargs)
|