forked from dmnfarrell/tkintertable
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTableModels.html
More file actions
2885 lines (2675 loc) · 118 KB
/
TableModels.html
File metadata and controls
2885 lines (2675 loc) · 118 KB
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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<meta name="generator" content="pdoc 0.6.1" />
<title>tkintertable.TableModels API documentation</title>
<meta name="description" content="Module implementing the TableModel class that manages data for
it's associated TableCanvas …" />
<link href='https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.0/normalize.min.css' rel='stylesheet'>
<link href='https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/8.0.0/sanitize.min.css' rel='stylesheet'>
<link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/github.min.css" rel="stylesheet">
<style>.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{font-weight:bold}#index h4 + ul{margin-bottom:.6em}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase;cursor:pointer}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}.admonition{padding:.1em .5em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>tkintertable.TableModels</code></h1>
</header>
<section id="section-intro">
<p>Module implementing the TableModel class that manages data for
it's associated TableCanvas.</p>
<p>Created Oct 2008
Copyright (C) Damien Farrell</p>
<p>This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.</p>
<p>This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the
GNU General Public License for more details.</p>
<p>You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307
USA</p>
<details class="source">
<summary>Source code</summary>
<pre><code class="python">#!/usr/bin/env python
"""
Module implementing the TableModel class that manages data for
it's associated TableCanvas.
Created Oct 2008
Copyright (C) Damien Farrell
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""
from __future__ import absolute_import, division, print_function
from .TableFormula import Formula
from . import Filtering
from types import *
from collections import OrderedDict
import operator
import string, types, copy
import pickle, os, sys, csv
class TableModel(object):
"""A base model for managing the data in a TableCanvas class"""
keywords = {'columnnames':'columnNames', 'columntypes':'columntypes',
'columnlabels':'columnlabels', 'columnorder':'columnOrder',
'colors':'colors'}
def __init__(self, newdict=None, rows=None, columns=None):
"""Constructor"""
self.initialiseFields()
self.setupModel(newdict, rows, columns)
return
def setupModel(self, newdict, rows=None, columns=None):
"""Create table model"""
if newdict != None:
self.data = copy.deepcopy(newdict)
for k in self.keywords:
if k in self.data:
self.__dict__[self.keywords[k]] = self.data[k]
del self.data[k]
#read in the record list order
if 'reclist' in self.data:
temp = self.data['reclist']
del self.data['reclist']
self.reclist = temp
else:
self.reclist = self.data.keys()
else:
#just make a new empty model
self.createEmptyModel()
if not set(self.reclist) == set(self.data.keys()):
print ('reclist does not match data keys')
#restore last column order
if hasattr(self, 'columnOrder') and self.columnOrder != None:
self.columnNames=[]
for i in self.columnOrder.keys():
self.columnNames.append(self.columnOrder[i])
i=i+1
self.defaulttypes = ['text', 'number']
#setup default display for column types
self.default_display = {'text' : 'showstring',
'number' : 'numtostring'}
#set default sort order as first col
if len(self.columnNames)>0:
self.sortkey = self.columnNames[0]
else:
self.sortkey = None
#add rows and cols if they are given in the constructor
if newdict == None:
if rows != None:
self.autoAddRows(rows)
if columns != None:
self.autoAddColumns(columns)
self.filteredrecs = None
return
def initialiseFields(self):
"""Create base fields, some of which are not saved"""
self.data = None # holds the table dict
self.colors = {} # holds cell colors
self.colors['fg']={}
self.colors['bg']={}
#default types
self.defaulttypes = ['text', 'number']
#list of editable column types
self.editable={}
self.nodisplay = []
self.columnwidths={} #used to store col widths, not held in saved data
return
def createEmptyModel(self):
"""Create the basic empty model dict"""
self.data = {}
# Define the starting column names and locations in the table.
self.columnNames = []
self.columntypes = {}
self.columnOrder = None
#record column labels for use in a table header
self.columnlabels={}
for colname in self.columnNames:
self.columnlabels[colname]=colname
self.reclist = list(self.data.keys())
return
def importCSV(self, filename, sep=','):
"""Import table data from a comma separated file."""
if not os.path.isfile(filename) or not os.path.exists(filename):
print ('no such file')
return None
#takes first row as field names
dictreader = csv.DictReader(open(filename, "r"), delimiter=sep)
dictdata = {}
count=0
for rec in dictreader:
dictdata[count]=rec
count=count+1
self.importDict(dictdata)
return
def importDict(self, newdata):
"""Try to create a table model from a dict of the form
{{'rec1': {'col1': 3, 'col2': 2}, ..}"""
#get cols from sub data keys
colnames = []
for k in newdata:
fields = newdata[k].keys()
for f in fields:
if not f in colnames:
colnames.append(f)
for c in colnames:
self.addColumn(c)
#add the data
self.data.update(newdata)
self.reclist = list(self.data.keys())
return
def getDefaultTypes(self):
"""Get possible field types for this table model"""
return self.defaulttypes
def getData(self):
"""Return the current data for saving"""
data = copy.deepcopy(self.data)
data['colors'] = self.colors
data['columnnames'] = self.columnNames
#we keep original record order
data['reclist'] = self.reclist
#record current col order
data['columnorder']={}
i=0
for name in self.columnNames:
data['columnorder'][i] = name
i=i+1
data['columntypes'] = self.columntypes
data['columnlabels'] = self.columnlabels
return data
def getAllCells(self):
"""Return a dict of the form rowname: list of cell contents
Useful for a simple table export for example"""
records={}
for row in range(len(self.reclist)):
recdata=[]
for col in range(len(self.columnNames)):
recdata.append(self.getValueAt(row,col))
records[row]=recdata
return records
def getColCells(self, colIndex):
"""Get the viewable contents of a col into a list"""
collist = []
if self.getColumnType(colIndex) == 'Link':
return ['xxxxxx']
else:
for row in range(len(self.reclist)):
v = self.getValueAt(row, colIndex)
collist.append(v)
return collist
def getlongestEntry(self, columnIndex):
"""Get the longest cell entry in the col"""
collist = self.getColCells(columnIndex)
maxw=5
for c in collist:
try:
w = len(str(c))
except UnicodeEncodeError:
pass
if w > maxw:
maxw = w
#print 'longest width', maxw
return maxw
def getRecordAtRow(self, rowIndex):
"""Get the entire record at the specifed row."""
name = self.getRecName(rowIndex)
record = self.data[name]
return record
def getCellRecord(self, rowIndex, columnIndex):
"""Get the data held in this row and column"""
value = None
colname = self.getColumnName(columnIndex)
coltype = self.columntypes[colname]
name = self.getRecName(rowIndex)
#print self.data[name]
if colname in self.data[name]:
celldata=self.data[name][colname]
else:
celldata=None
return celldata
def deleteCellRecord(self, rowIndex, columnIndex):
"""Remove the cell data at this row/column"""
colname = self.getColumnName(columnIndex)
coltype = self.columntypes[colname]
name = self.getRecName(rowIndex)
if colname in self.data[name]:
del self.data[name][colname]
return
def getRecName(self, rowIndex):
"""Get record name from row number"""
if len(self.reclist)==0:
return None
if self.filteredrecs != None:
name = self.filteredrecs[rowIndex]
else:
name = self.reclist[rowIndex]
return name
def setRecName(self, newname, rowIndex):
"""Set the record name to another value - requires re-setting in all
dicts that this rec is referenced"""
if len(self.reclist)==0:
return None
currname = self.getRecName(rowIndex)
self.reclist[rowIndex] = newname
temp = copy.deepcopy(self.data[currname])
self.data[newname] = temp
#self.data[newname]['Name'] = newname
del self.data[currname]
for key in ['bg', 'fg']:
if currname in self.colors[key]:
temp = copy.deepcopy(self.colors[key][currname])
self.colors[key][newname] = temp
del self.colors[key][currname]
print ('renamed')
#would also need to resolve all refs to this rec in formulas here!
return
def getRecordAttributeAtColumn(self, rowIndex=None, columnIndex=None,
recName=None, columnName=None):
"""Get the attribute of the record at the specified column index.
This determines what will be displayed in the cell"""
value = None
if columnName != None and recName != None:
if columnName not in self.data[recName]:
return ''
cell = self.data[recName][columnName]
else:
cell = self.getCellRecord(rowIndex, columnIndex)
columnName = self.getColumnName(columnIndex)
if cell == None:
cell=''
# Set the value based on the data record field
coltype = self.columntypes[columnName]
if Formula.isFormula(cell) == True:
value = self.doFormula(cell)
return value
if not type(cell) is dict:
if coltype == 'text' or coltype == 'Text':
value = cell
elif coltype == 'number':
value = str(cell)
else:
value = 'other'
if value==None:
value=''
return value
def getRecordIndex(self, recname):
rowIndex = int(self.reclist.index(recname))
return rowIndex
def setSortOrder(self, columnIndex=None, columnName=None, reverse=0):
"""Changes the order that records are sorted in, which will
be reflected in the table upon redrawing"""
if columnName != None and columnName in self.columnNames:
self.sortkey = columnName
elif columnIndex != None:
self.sortkey = self.getColumnName(columnIndex)
else:
return
self.reclist = list(self.createSortMap(self.reclist, self.sortkey, reverse))
if self.filteredrecs != None:
self.filteredrecs = self.createSortMap(self.filteredrecs, self.sortkey, reverse)
return
def createSortMap(self, names, sortkey, reverse=0):
"""Create a sort mapping for given list"""
recdata = []
for rec in names:
recdata.append(self.getRecordAttributeAtColumn(recName=rec, columnName=sortkey))
#try create list of floats if col has numbers only
try:
recdata = self.toFloats(recdata)
except:
pass
smap = zip(names, recdata)
#sort the mapping by the second key
smap = sorted(smap, key=operator.itemgetter(1), reverse=reverse)
#now sort the main reclist by the mapping order
sortmap = map(operator.itemgetter(0), smap)
return sortmap
def toFloats(self, l):
x=[]
for i in l:
if i == '':
x.append(0.0)
else:
x.append(float(i))
return x
'''def getSortIndex(self):
"""Return the current sort order index"""
if self.sortcolumnIndex:
return self.sortcolumnIndex
else:
return 0'''
def moveColumn(self, oldcolumnIndex, newcolumnIndex):
"""Changes the order of columns"""
self.oldnames = self.columnNames
self.columnNames=[]
#write out a new column names list - tedious
moved = self.oldnames[oldcolumnIndex]
del self.oldnames[oldcolumnIndex]
#print self.oldnames
i=0
for c in self.oldnames:
if i==newcolumnIndex:
self.columnNames.append(moved)
self.columnNames.append(c)
i=i+1
#if new col is at end just append
if moved not in self.columnNames:
self.columnNames.append(moved)
return
def getNextKey(self):
"""Return the next numeric key in the dict"""
num = len(self.reclist)+1
return num
def addRow(self, key=None, **kwargs):
"""Add a row"""
if key == '':
return
if key==None:
key = self.getNextKey()
if key in self.data or key in self.reclist:
print ('name already present!!')
return
self.data[key]={}
for k in kwargs:
if not k in self.columnNames:
self.addColumn(k)
self.data[key][k] = str(kwargs[k])
self.reclist.append(key)
return key
def deleteRow(self, rowIndex=None, key=None, update=True):
"""Delete a row"""
if key == None or not key in self.reclist:
key = self.getRecName(rowIndex)
del self.data[key]
if update==True:
self.reclist.remove(key)
return
def deleteRows(self, rowlist=None):
"""Delete multiple or all rows"""
if rowlist == None:
rowlist = range(len(self.reclist))
names = [self.getRecName(i) for i in rowlist]
for name in names:
self.deleteRow(key=name, update=True)
return
def addColumn(self, colname=None, coltype=None):
"""Add a column"""
index = self.getColumnCount()+ 1
if colname == None:
colname=str(index)
if colname in self.columnNames:
#print 'name is present!'
return
self.columnNames.append(colname)
self.columnlabels[colname] = colname
if coltype == None:
self.columntypes[colname]='text'
else:
self.columntypes[colname]=coltype
return
def deleteColumn(self, columnIndex):
"""delete a column"""
colname = self.getColumnName(columnIndex)
self.columnNames.remove(colname)
del self.columnlabels[colname]
del self.columntypes[colname]
#remove this field from every record
for recname in self.reclist:
if colname in self.data[recname]:
del self.data[recname][colname]
if self.sortkey != None:
currIndex = self.getColumnIndex(self.sortkey)
if columnIndex == currIndex:
self.setSortOrder(0)
#print 'column deleted'
#print 'new cols:', self.columnNames
return
def deleteColumns(self, cols=None):
"""Remove all cols or list provided"""
if cols == None:
cols = self.columnNames
if self.getColumnCount() == 0:
return
for col in cols:
self.deleteColumn(col)
return
def autoAddRows(self, numrows=None):
"""Automatically add x number of records"""
rows = self.getRowCount()
ints = [i for i in self.reclist if isinstance(i, int)]
if len(ints)>0:
start = max(ints)+1
else:
start = 0
#we don't use addRow as it's too slow
keys = range(start,start+numrows)
#make sure no keys are present already
keys = list(set(keys)-set(self.reclist))
newdata = {}
for k in keys:
newdata[k] = {}
self.data.update(newdata)
self.reclist.extend(newdata.keys())
return keys
def autoAddColumns(self, numcols=None):
"""Automatically add x number of cols"""
#alphabet = string.lowercase[:26]
alphabet = string.ascii_lowercase
currcols=self.getColumnCount()
#find where to start
start = currcols + 1
end = currcols + numcols + 1
new = []
for n in range(start, end):
new.append(str(n))
#check if any of these colnames present
common = set(new) & set(self.columnNames)
extra = len(common)
end = end + extra
for x in range(start, end):
self.addColumn(str(x))
return
def relabel_Column(self, columnIndex, newname):
"""Change the column label - can be used in a table header"""
colname = self.getColumnName(columnIndex)
self.columnlabels[colname]=newname
return
def getColumnType(self, columnIndex):
"""Get the column type"""
colname = self.getColumnName(columnIndex)
coltype = self.columntypes[colname]
return coltype
def getColumnCount(self):
"""Returns the number of columns in the data model."""
return len(self.columnNames)
def getColumnName(self, columnIndex):
"""Returns the name of the given column by columnIndex."""
return self.columnNames[columnIndex]
def getColumnLabel(self, columnIndex):
"""Returns the label for this column"""
colname = self.getColumnName(columnIndex)
return self.columnlabels[colname]
def getColumnIndex(self, columnName):
"""Returns the column index for this column"""
colindex = self.columnNames.index(columnName)
return colindex
def getColumnData(self, columnIndex=None, columnName=None,
filters=None):
"""Return the data in a list for this col,
filters is a tuple of the form (key,value,operator,bool)"""
if columnIndex != None and columnIndex < len(self.columnNames):
columnName = self.getColumnName(columnIndex)
names = Filtering.doFiltering(searchfunc=self.filterBy,
filters=filters)
coldata = [self.data[n][columnName] for n in names]
return coldata
def getColumns(self, colnames, filters=None, allowempty=True):
"""Get column data for multiple cols, with given filter options,
filterby: list of tuples of the form (key,value,operator,bool)
allowempty: boolean if false means rows with empty vals for any
required fields are not returned
returns: lists of column data"""
def evaluate(l):
for i in l:
if i == '' or i == None:
return False
return True
coldata=[]
for c in colnames:
vals = self.getColumnData(columnName=c, filters=filters)
coldata.append(vals)
if allowempty == False:
result = [i for i in zip(*coldata) if evaluate(i) == True]
coldata = zip(*result)
return coldata
def getDict(self, colnames, filters=None):
"""Get the model data as a dict for given columns with filter options"""
data={}
names = self.reclist
cols = self.getColumns(colnames, filters)
coldata = zip(*cols)
for name,cdata in zip(names, coldata):
data[name] = dict(zip(colnames,cdata))
return data
def filterBy(self, filtercol, value, op='contains', userecnames=False,
progresscallback=None):
"""The searching function that we apply to the model data.
This is used in Filtering.doFiltering to find the required recs
according to column, value and an operator"""
funcs = Filtering.operatornames
floatops = ['=','>','<']
func = funcs[op]
data = self.data
#coltype = self.columntypes[filtercol]
names=[]
for rec in self.reclist:
if filtercol in data[rec]:
#try to do float comparisons if required
if op in floatops:
try:
#print float(data[rec][filtercol])
item = float(data[rec][filtercol])
v = float(value)
if func(v, item) == True:
names.append(rec)
continue
except:
pass
if filtercol == 'name' and userecnames == True:
item = rec
else:
item = str(data[rec][filtercol])
if func(value, item):
names.append(rec)
return names
def getRowCount(self):
"""Returns the number of rows in the table model."""
return len(self.reclist)
def getValueAt(self, rowIndex, columnIndex):
"""Returns the cell value at location specified
by columnIndex and rowIndex."""
value = self.getRecordAttributeAtColumn(rowIndex, columnIndex)
return value
def setValueAt(self, value, rowIndex, columnIndex):
"""Changed the dictionary when cell is updated by user"""
name = self.getRecName(rowIndex)
colname = self.getColumnName(columnIndex)
coltype = self.columntypes[colname]
if coltype == 'number':
try:
if value == '': #need this to allow deletion of values
self.data[name][colname] = ''
else:
self.data[name][colname] = float(value)
except:
pass
else:
self.data[name][colname] = value
return
def setFormulaAt(self, f, rowIndex, columnIndex):
"""Set a formula at cell given"""
name = self.getRecName(rowIndex)
colname = self.getColumnName(columnIndex)
coltype = self.columntypes[colname]
rec = {}
rec['formula'] = f
self.data[name][colname] = rec
return
def getColorAt(self, rowIndex, columnIndex, key='bg'):
"""Return color of that record field for the table"""
name = self.getRecName(rowIndex)
colname = self.getColumnName(columnIndex)
if name in self.colors[key] and colname in self.colors[key][name]:
return self.colors[key][name][colname]
else:
return None
def setColorAt(self, rowIndex, columnIndex, color, key='bg'):
"""Set color"""
name = self.getRecName(rowIndex)
colname = self.getColumnName(columnIndex)
if not name in self.colors[key]:
self.colors[key][name] = {}
self.colors[key][name][colname] = str(color)
return
def resetcolors(self):
"""Remove all color formatting"""
self.colors={}
self.colors['fg']={}
self.colors['bg']={}
return
def getRecColNames(self, rowIndex, ColIndex):
"""Returns the rec and col name as a tuple"""
recname = self.getRecName(rowIndex)
colname = self.getColumnName(ColIndex)
return (recname, colname)
def getRecAtRow(self, recname, colname, offset=1, dim='y'):
"""Get the record name at a specified offset in the current
table from the record given, by using the current sort order"""
thisrow = self.getRecordIndex(recname)
thiscol = self.getColumnIndex(colname)
#table goto next row
if dim == 'y':
nrow = thisrow + offset
ncol = thiscol
else:
nrow = thisrow
ncol = thiscol + offset
newrecname, newcolname = self.getRecColNames(nrow, ncol)
print ('recname, colname', recname, colname)
print ('thisrow, col', thisrow, thiscol)
return newrecname, newcolname
def appendtoFormula(self, formula, rowIndex, colIndex):
"""Add the input cell to the formula"""
cellRec = getRecColNames(rowIndex, colIndex)
formula.append(cellRec)
return
def doFormula(self, cellformula):
"""Evaluate the formula for a cell and return the result"""
value = Formula.doFormula(cellformula, self.data)
return value
def copyFormula(self, cellval, row, col, offset=1, dim='y'):
"""Copy a formula down or across, using the provided offset"""
import re
frmla = Formula.getFormula(cellval)
#print 'formula', frmla
newcells=[]
cells, ops = Formula.readExpression(frmla)
for c in cells:
print (c)
if type(c) is not ListType:
nc = c
else:
recname = c[0]
colname = c[1]
nc = list(self.getRecAtRow(recname, colname, offset, dim=dim))
newcells.append(nc)
newformula = Formula.doExpression(newcells, ops, getvalues=False)
return newformula
def merge(self, model, key='name', fields=None):
"""Merge another table model with this one based on a key field,
we only add records from the new model where the key is present
in both models"""
if fields == None: fields = model.columnNames
for rec in self.reclist:
if not key in self.data[rec]:
continue
for new in model.reclist:
if not key in model.data[new]:
continue
if self.data[rec][key] == model.data[new][key]:
#if new == rec:
for f in fields:
if not f in model.data[rec]:
continue
if not f in self.columnNames:
self.addColumn(f)
self.data[rec][f] = model.data[rec][f]
return
def save(self, filename=None):
"""Save model to file"""
if filename == None:
return
data = self.getData()
fd = open(filename,'wb')
pickle.dump(data,fd)
fd.close()
return
def load(self, filename):
"""Load model from pickle file"""
fd=open(filename,'rb')
data = pickle.load(fd)
self.setupModel(data)
return
def copy(self):
"""Return a copy of this model"""
M = TableModel()
data = self.getData()
M.setupModel(data)
return M
def __repr__(self):
return 'Table Model with %s rows' %len(self.reclist)</code></pre>
</details>
</section>
<section>
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="tkintertable.TableModels.TableModel"><code class="flex name class">
<span>class <span class="ident">TableModel</span></span>
<span>(</span><span>newdict=None, rows=None, columns=None)</span>
</code></dt>
<dd>
<section class="desc"><p>A base model for managing the data in a TableCanvas class</p>
<p>Constructor</p></section>
<details class="source">
<summary>Source code</summary>
<pre><code class="python">class TableModel(object):
"""A base model for managing the data in a TableCanvas class"""
keywords = {'columnnames':'columnNames', 'columntypes':'columntypes',
'columnlabels':'columnlabels', 'columnorder':'columnOrder',
'colors':'colors'}
def __init__(self, newdict=None, rows=None, columns=None):
"""Constructor"""
self.initialiseFields()
self.setupModel(newdict, rows, columns)
return
def setupModel(self, newdict, rows=None, columns=None):
"""Create table model"""
if newdict != None:
self.data = copy.deepcopy(newdict)
for k in self.keywords:
if k in self.data:
self.__dict__[self.keywords[k]] = self.data[k]
del self.data[k]
#read in the record list order
if 'reclist' in self.data:
temp = self.data['reclist']
del self.data['reclist']
self.reclist = temp
else:
self.reclist = self.data.keys()
else:
#just make a new empty model
self.createEmptyModel()
if not set(self.reclist) == set(self.data.keys()):
print ('reclist does not match data keys')
#restore last column order
if hasattr(self, 'columnOrder') and self.columnOrder != None:
self.columnNames=[]
for i in self.columnOrder.keys():
self.columnNames.append(self.columnOrder[i])
i=i+1
self.defaulttypes = ['text', 'number']
#setup default display for column types
self.default_display = {'text' : 'showstring',
'number' : 'numtostring'}
#set default sort order as first col
if len(self.columnNames)>0:
self.sortkey = self.columnNames[0]
else:
self.sortkey = None
#add rows and cols if they are given in the constructor
if newdict == None:
if rows != None:
self.autoAddRows(rows)
if columns != None:
self.autoAddColumns(columns)
self.filteredrecs = None
return
def initialiseFields(self):
"""Create base fields, some of which are not saved"""
self.data = None # holds the table dict
self.colors = {} # holds cell colors
self.colors['fg']={}
self.colors['bg']={}
#default types
self.defaulttypes = ['text', 'number']
#list of editable column types
self.editable={}
self.nodisplay = []
self.columnwidths={} #used to store col widths, not held in saved data
return
def createEmptyModel(self):
"""Create the basic empty model dict"""
self.data = {}
# Define the starting column names and locations in the table.
self.columnNames = []
self.columntypes = {}
self.columnOrder = None
#record column labels for use in a table header
self.columnlabels={}
for colname in self.columnNames:
self.columnlabels[colname]=colname
self.reclist = list(self.data.keys())
return
def importCSV(self, filename, sep=','):
"""Import table data from a comma separated file."""
if not os.path.isfile(filename) or not os.path.exists(filename):
print ('no such file')
return None
#takes first row as field names
dictreader = csv.DictReader(open(filename, "r"), delimiter=sep)
dictdata = {}
count=0
for rec in dictreader:
dictdata[count]=rec
count=count+1
self.importDict(dictdata)
return
def importDict(self, newdata):
"""Try to create a table model from a dict of the form
{{'rec1': {'col1': 3, 'col2': 2}, ..}"""
#get cols from sub data keys
colnames = []
for k in newdata:
fields = newdata[k].keys()
for f in fields:
if not f in colnames:
colnames.append(f)
for c in colnames:
self.addColumn(c)
#add the data
self.data.update(newdata)
self.reclist = list(self.data.keys())
return
def getDefaultTypes(self):
"""Get possible field types for this table model"""
return self.defaulttypes
def getData(self):
"""Return the current data for saving"""
data = copy.deepcopy(self.data)
data['colors'] = self.colors
data['columnnames'] = self.columnNames
#we keep original record order
data['reclist'] = self.reclist
#record current col order
data['columnorder']={}
i=0
for name in self.columnNames:
data['columnorder'][i] = name
i=i+1
data['columntypes'] = self.columntypes
data['columnlabels'] = self.columnlabels
return data
def getAllCells(self):
"""Return a dict of the form rowname: list of cell contents
Useful for a simple table export for example"""
records={}
for row in range(len(self.reclist)):
recdata=[]
for col in range(len(self.columnNames)):
recdata.append(self.getValueAt(row,col))
records[row]=recdata
return records
def getColCells(self, colIndex):