forked from slightlynybbled/tk_tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgroups.py
More file actions
484 lines (374 loc) · 15.1 KB
/
groups.py
File metadata and controls
484 lines (374 loc) · 15.1 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
import tkinter as tk
from collections import OrderedDict
import tk_tools
import xlrd
import xlwt
class Grid(tk.Frame):
"""
Creates a grid of widgets (intended to be subclassed)
"""
def __init__(self, parent, num_of_columns: int, headers: list=None, **options):
"""
Initialization of the grid object
:param parent: the tk parent element of this frame
:param num_of_columns: the number of columns contained of the grid
:param headers: a list containing the names of the column headers
"""
tk.Frame.__init__(self, parent, padx=3, pady=3, borderwidth=2, **options)
self.grid()
self.headers = list()
self.rows = list()
self.num_of_columns = num_of_columns
# do some validation
if headers:
if len(headers) != num_of_columns:
raise ValueError
for i, element in enumerate(headers):
label = tk.Label(self, text=str(element), relief=tk.GROOVE)
label.grid(row=0, column=i, sticky='E,W')
self.headers.append(label)
def add_row(self, data: list):
"""
Adds a row of data based on the entered data
:param data: row of data as a list
:return: None
"""
raise NotImplementedError
def _redraw(self):
"""
Forgets the current layout and redraws with the most recent information
:return:
"""
for row in self.rows:
for widget in row:
widget.grid_forget()
offset = 0 if not self.headers else 1
for i, row in enumerate(self.rows):
for j, widget in enumerate(row):
widget.grid(row=i+offset, column=j)
def remove_row(self, row_number: int=-1):
"""
Removes a specified row of data
:param row_number: the row to remove (defaults to the last row)
:return: None
"""
if len(self.rows) == 0:
return
row = self.rows.pop(row_number)
for widget in row:
widget.destroy()
def clear(self):
"""
Removes all elements of the grid
:return: None
"""
for i in range(len(self.rows)):
self.remove_row(0)
class LabelGrid(Grid):
"""
A table-like display widget
"""
def __init__(self, parent, num_of_columns: int, headers: list=None, **options):
"""
Initialization of the label grid object
:param parent: the tk parent element of this frame
:param num_of_columns: the number of columns contained of the grid
:param headers: a list containing the names of the column headers
"""
super().__init__(parent, num_of_columns, headers, **options)
def add_row(self, data: list):
"""
Add a row of data to the current widget
:param data: a row of data
:return: None
"""
# validation
if self.headers:
if len(self.headers) != len(data):
raise ValueError
offset = 0 if not self.headers else 1
row = list()
for i, element in enumerate(data):
label = tk.Label(self, text=str(element), relief=tk.GROOVE)
label.grid(row=len(self.rows) + offset, column=i, sticky='E,W')
row.append(label)
self.rows.append(row)
class EntryGrid(Grid):
"""
Add a spreadsheet-like grid of entry widgets
"""
def __init__(self, parent, num_of_columns: int, headers: list=None, **options):
"""
Initialization of the entry grid object
:param parent: the tk parent element of this frame
:param num_of_columns: the number of columns contained of the grid
:param headers: a list containing the names of the column headers
"""
super().__init__(parent, num_of_columns, headers, **options)
def add_row(self, data: list=None):
"""
Add a row of data to the current widget, add a <Tab> binding to the
last element of the last row, and set the focus at the beginning of the next row
:param data: a row of data
:return: None
"""
# validation
if self.headers and data:
if len(self.headers) != len(data):
raise ValueError
offset = 0 if not self.headers else 1
row = list()
if data:
for i, element in enumerate(data):
contents = '' if element is None else str(element)
entry = tk.Entry(self)
entry.insert(0, contents)
entry.grid(row=len(self.rows) + offset, column=i, sticky='E,W')
row.append(entry)
else:
for i in range(self.num_of_columns):
entry = tk.Entry(self)
entry.grid(row=len(self.rows) + offset, column=i, sticky='E,W')
row.append(entry)
self.rows.append(row)
# clear all bindings
for row in self.rows:
for widget in row:
widget.unbind('<Tab>')
def add(e):
self.add_row()
last_entry = self.rows[-1][-1]
last_entry.bind('<Tab>', add)
e = self.rows[-1][0]
e.focus_set()
self._redraw()
def _read_as_dict(self):
"""
Read the data contained in all entries as a list of
dictionaries with the headers as the dictionary keys
:return: list of dicts containing all tabular data
"""
data = list()
for row in self.rows:
row_data = OrderedDict()
for i, header in enumerate(self.headers):
row_data[header.cget('text')] = row[i].get()
data.append(row_data)
return data
def _read_as_table(self):
"""
Read the data contained in all entries as a list of
lists containing all of the data
:return: list of dicts containing all tabular data
"""
rows = list()
for row in self.rows:
rows.append([row[i].get() for i in range(self.num_of_columns)])
return rows
def read(self, as_dicts=True):
"""
Read the data from the entry fields
:param as_dicts: True if the data is desired as a list of dicts, else False
:return:
"""
if as_dicts:
return self._read_as_dict()
else:
return self._read_as_table()
class KeyValueEntry(tk.Frame):
"""
Creates a key-value frame so common in modern GUI
"""
def __init__(self, parent, keys: list, defaults: list=None,
unit_labels: list=None, enables: list=None,
title=None, on_change_callback=None, **options):
"""
Key/Value constructor
:param parent: the parent frame
:param keys: the keys represented
:param defaults: default values for each key
:param unit_labels: unit labels for each key (to the right of the value)
:param enables: True/False for each key
:param title: The title of the block
:param on_change_callback: a function callback when any element is changed
:param options: frame tk options
"""
tk.Frame.__init__(self, parent,
borderwidth=2,
padx=5, pady=5,
**options)
self.defaults = defaults
row_offset = 0
columns = 3 if unit_labels else 2
if title:
self.title = tk.Label(self, text=title)
self.title.grid(row=row_offset, column=0, columnspan=columns)
row_offset += 1
def callback(event):
on_change_callback()
self.keys = []
self.values = []
self.units = []
for i, key in enumerate(keys):
label = tk.Label(self, text=key)
label.grid(row=row_offset, column=0, sticky='E')
self.keys.append(label)
entry = tk.Entry(self)
entry.grid(row=row_offset, column=1)
self.values.append(entry)
if self.defaults:
entry.insert(0, self.defaults[i])
if enables:
if not enables[i]:
entry.config(state='disabled')
if unit_labels:
unit = tk.Label(self, text=unit_labels[i])
unit.grid(row=row_offset, column=2, sticky='W')
self.units.append(unit)
if on_change_callback:
entry.bind('<Return>', callback)
entry.bind('<Tab>', callback)
row_offset += 1
def reset(self):
"""
Clears all entries
:return: None
"""
for i, entry in enumerate(self.values):
entry.delete(0, tk.END)
entry.insert(0, self.defaults[i])
def change_enables(self, enables_list: list):
"""
Enable/disable inputs
:param enables_list: list containing enables for each key
:return: None
"""
for i, entry in enumerate(self.values):
if enables_list[i]:
entry.config(state=tk.NORMAL)
def load(self, data: dict):
"""
Load values into the key/values via dict
:param data: dict containing the key/values that should be inserted
:return:
"""
for i, label in enumerate(self.keys):
key = label.cget('text')
if key in data.keys():
entry_was_enabled = True if self.values[i].cget('state') == 'normal' else False
if not entry_was_enabled:
self.values[i].config(state='normal')
self.values[i].delete(0, tk.END)
self.values[i].insert(0, str(data[key]))
if not entry_was_enabled:
self.values[i].config(state='disabled')
def get(self):
"""
Retrieve the GUI elements for program use
:return: a dictionary containing all of the data from the key/value entries
"""
data = dict()
for label, entry in zip(self.keys, self.values):
data[label.cget('text')] = entry.get()
return data
class SpreadSheetReader(tk.Frame):
def __init__(self, parent, path, rows_to_display=20, cols_do_display=8, sheetname=None, **options):
tk.Frame.__init__(self, parent, **options)
self.header = tk.Label(self, text='Select the column you wish to import')
self.header.grid(row=0, column=0, columnspan=4)
self.entry_grid = tk_tools.EntryGrid(self, num_of_columns=8)
self.entry_grid.grid(row=1, column=0, columnspan=4, rowspan=4)
self.move_page_up_btn = tk.Button(self, text='^\n^', command=lambda: self.move_up(page=True))
self.move_page_up_btn.grid(row=1, column=4, sticky='NS')
self.move_page_up_btn = tk.Button(self, text='^', command=self.move_up)
self.move_page_up_btn.grid(row=2, column=4, sticky='NS')
self.move_page_down_btn = tk.Button(self, text='v', command=self.move_down)
self.move_page_down_btn.grid(row=3, column=4, sticky='NS')
self.move_page_down_btn = tk.Button(self, text='v\nv', command=lambda: self.move_down(page=True))
self.move_page_down_btn.grid(row=4, column=4, sticky='NS')
# add buttons to navigate the spreadsheet
self.move_page_left_btn = tk.Button(self, text='<<', command=lambda: self.move_left(page=True))
self.move_page_left_btn.grid(row=5, column=0, sticky='EW')
self.move_left_btn = tk.Button(self, text='<', command=self.move_left)
self.move_left_btn.grid(row=5, column=1, sticky='EW')
self.move_right_btn = tk.Button(self, text='>', command=self.move_right)
self.move_right_btn.grid(row=5, column=2, sticky='EW')
self.move_page_right_btn = tk.Button(self, text='>>', command=lambda: self.move_right(page=True))
self.move_page_right_btn.grid(row=5, column=3, sticky='EW')
self.path = path
self.sheetname = sheetname
self.rows_to_display = rows_to_display
self.cols_to_display = cols_do_display
self.current_position = (0, 0)
self.read_xl(sheetname=self.sheetname)
def read_xl(self, row_number=0, column_number=0, sheetname=None, sheetnum=0):
workbook = xlrd.open_workbook(self.path)
if sheetname:
sheet = workbook.sheet_by_name(sheetname)
else:
sheet = workbook.sheet_by_index(sheetnum)
for i, row in enumerate(sheet.get_rows()):
if i >= row_number:
data = row[column_number:column_number + self.cols_to_display]
data = [point.value for point in data]
self.entry_grid.add_row(data=data)
if i >= (self.rows_to_display + row_number):
break
def move_right(self, page=False):
row_pos, col_pos = self.current_position
self.entry_grid.clear()
if page:
self.current_position = (row_pos, col_pos + self.cols_to_display)
else:
self.current_position = (row_pos, col_pos + 1)
self.read_xl(*self.current_position, sheetname=self.sheetname)
def move_left(self, page=False):
row_pos, col_pos = self.current_position
if not page and col_pos == 0:
return
if page and col_pos < self.cols_to_display:
return
self.entry_grid.clear()
if page:
self.current_position = (row_pos, col_pos - self.cols_to_display)
else:
self.current_position = (row_pos, col_pos - 1)
self.read_xl(*self.current_position, sheetname=self.sheetname)
def move_down(self, page=False):
row_pos, col_pos = self.current_position
self.entry_grid.clear()
if page:
self.current_position = (row_pos + self.rows_to_display, col_pos)
else:
self.current_position = (row_pos + 1, col_pos)
self.read_xl(*self.current_position, sheetname=self.sheetname)
def move_up(self, page=False):
row_pos, col_pos = self.current_position
if not page and row_pos == 0:
return
if page and row_pos < self.rows_to_display:
return
self.entry_grid.clear()
if page:
self.current_position = (row_pos - self.rows_to_display, col_pos)
else:
self.current_position = (row_pos - 1, col_pos)
self.read_xl(*self.current_position, sheetname=self.sheetname)
if __name__ == '__main__':
root = tk.Tk()
entry_grid = EntryGrid(root, 3, ['L0', 'L1', 'L2'])
entry_grid.grid(row=0, column=0)
def add_row():
row = [1, 2, 3]
entry_grid.add_row(row)
add_row_btn = tk.Button(text='Add Row', command=add_row)
add_row_btn.grid(row=1, column=0)
def remove_row():
entry_grid.remove_row(0)
remove_row_btn = tk.Button(text='Remove Row', command=remove_row)
remove_row_btn.grid(row=2, column=0)
def read():
print(entry_grid.read(as_dicts=False))
read_btn = tk.Button(text='Read', command=read)
read_btn.grid(row=3, column=0)
root.mainloop()