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
1170 lines (931 loc) · 36.8 KB
/
groups.py
File metadata and controls
1170 lines (931 loc) · 36.8 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
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.font import Font
import datetime
import calendar
from collections import OrderedDict
try:
from tk_tools.images import minus
except ImportError:
minus = ""
class _Grid(ttk.Frame):
padding = 3
"""
Creates a grid of widgets (intended to be subclassed).
: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
"""
def __init__(self, parent, num_of_columns: int, headers: list = None, **options):
self._parent = parent
super().__init__(self._parent, padding=3, borderwidth=2, **options)
self.grid()
self.headers = list()
self._rows = list()
self.num_of_columns = num_of_columns
self._has_row_labels = False
# do some validation
if headers:
if len(headers) != num_of_columns:
raise ValueError
for i, element in enumerate(headers):
label = ttk.Label(
self, text=str(element), relief=tk.GROOVE, padding=self.padding
)
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: None
"""
for widget in self.headers:
widget.grid_forget()
for row in self._rows:
for widget in row:
widget.grid_forget()
for i, widget in enumerate(self.headers):
widget.grid(row=0, column=i, sticky="E,W")
r = 0 if not self.headers else 1
for i, row in enumerate(self._rows):
for j, widget in enumerate(row):
widget.grid(row=i + r, 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.
: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
"""
def __init__(self, parent, num_of_columns: int, headers: list = None, **options):
self._parent = parent
super().__init__(self._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
if len(data) != self.num_of_columns:
raise ValueError
offset = 0 if not self.headers else 1
row = list()
for i, element in enumerate(data):
label = ttk.Label(
self, text=str(element), relief=tk.GROOVE, padding=self.padding
)
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.
: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
"""
def __init__(self, parent, num_of_columns: int, headers: list = None, **options):
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 = ttk.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 = ttk.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 list of dicts required, else False
:return: entries as a dict or table
"""
if as_dicts:
return self._read_as_dict()
else:
return self._read_as_table()
class ButtonGrid(_Grid):
"""
A grid of buttons.
: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
"""
def __init__(self, parent, num_of_columns: int, headers: list = None, **options):
super().__init__(parent, num_of_columns, headers, **options)
def add_row(self, data: list, row_label: str = None):
"""
Add a row of buttons each with their own callbacks to the
current widget. Each element in `data` will consist of a
label and a command.
:param data: a list of tuples of the form ('label', <callback>)
:return: None
"""
# validation
if self.headers and data:
if len(self.headers) != len(data):
raise ValueError
for widget in self.headers:
widget.grid_forget()
for row in self._rows:
for widget in row:
widget.grid_forget()
row = list()
if row_label is not None:
lbl = tk.Label(self, text=row_label)
row.append(lbl)
for i, e in enumerate(data):
if not isinstance(e, tuple):
raise ValueError(
"all elements must be a tuple " 'consisting of ("label", <command>)'
)
label, command = e
button = tk.Button(
self,
text=str(label),
relief=tk.RAISED,
command=command,
padx=self.padding,
pady=self.padding,
)
row.append(button)
self._rows.append(row)
# check if row has row labels
has_row_labels = False
for row in self._rows:
if isinstance(row[0], tk.Label):
has_row_labels = True
break
r = 0 if not self.headers else 1
for i, widget in enumerate(self.headers):
if has_row_labels:
widget.grid(row=0, column=i + 1, sticky="ew")
else:
widget.grid(row=0, column=i, sticky="ew")
for i, row in enumerate(self._rows):
for j, widget in enumerate(row):
widget.grid(row=i + r, column=j, sticky="ew")
class KeyValueEntry(ttk.Frame):
"""
Creates a key-value input/output frame.
: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
"""
def __init__(
self,
parent,
keys: list,
defaults: list = None,
unit_labels: list = None,
enables: list = None,
title: str = None,
on_change_callback: callable = None,
**options
):
self._parent = parent
super().__init__(self._parent, borderwidth=2, padding=5, **options)
# some checks before proceeding
if defaults:
if len(keys) != len(defaults):
raise ValueError("unit_labels length does not " "match keys length")
if unit_labels:
if len(keys) != len(unit_labels):
raise ValueError("unit_labels length does not " "match keys length")
if enables:
if len(keys) != len(enables):
raise ValueError("enables length does not " "match keys length")
self.keys = []
self.values = []
self.defaults = []
self.unit_labels = []
self.enables = []
self.callback = on_change_callback
if title is not None:
self.title = ttk.Label(self, text=title)
self.title.grid(row=0, column=0, columnspan=3)
else:
self.title = None
for i in range(len(keys)):
self.add_row(
key=keys[i],
default=defaults[i] if defaults else None,
unit_label=unit_labels[i] if unit_labels else None,
enable=enables[i] if enables else None,
)
def add_row(
self, key: str, default: str = None, unit_label: str = None, enable: bool = None
):
"""
Add a single row and re-draw as necessary
:param key: the name and dict accessor
:param default: the default value
:param unit_label: the label that should be \
applied at the right of the entry
:param enable: the 'enabled' state (defaults to True)
:return:
"""
self.keys.append(ttk.Label(self, text=key))
self.defaults.append(default)
self.unit_labels.append(ttk.Label(self, text=unit_label if unit_label else ""))
self.enables.append(enable)
self.values.append(ttk.Entry(self))
row_offset = 1 if self.title is not None else 0
for i in range(len(self.keys)):
self.keys[i].grid_forget()
self.keys[i].grid(row=row_offset, column=0, sticky="e")
self.values[i].grid(row=row_offset, column=1)
if self.unit_labels[i]:
self.unit_labels[i].grid(row=row_offset, column=3, sticky="w")
if self.defaults[i]:
self.values[i].config(state=tk.NORMAL)
self.values[i].delete(0, tk.END)
self.values[i].insert(0, self.defaults[i])
if self.enables[i] in [True, None]:
self.values[i].config(state=tk.NORMAL)
elif self.enables[i] is False:
self.values[i].config(state=tk.DISABLED)
row_offset += 1
# strip <Return> and <Tab> bindings, add callbacks to all entries
self.values[i].unbind("<Return>")
self.values[i].unbind("<Tab>")
if self.callback is not None:
def callback(event):
self.callback()
self.values[i].bind("<Return>", callback)
self.values[i].bind("<Tab>", callback)
def reset(self):
"""
Clears all entries.
:return: None
"""
for i in range(len(self.values)):
self.values[i].delete(0, tk.END)
if self.defaults[i] is not None:
self.values[i].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)
else:
entry.config(state=tk.DISABLED)
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: None
"""
for i, label in enumerate(self.keys):
key = label.cget("text")
if key in data.keys():
entry_was_enabled = str(self.values[i].cget("state")) == "normal"
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
def _get_calendar(locale, fwday):
# instantiate proper calendar class
if locale is None:
return calendar.TextCalendar(fwday)
else:
return calendar.LocaleTextCalendar(fwday, locale)
class Calendar(ttk.Frame):
"""
Graphical date selection widget, with callbacks. To change
the language, use the ``locale`` library with the appropriate
settings for the target language. For instance, to display
the ``Calendar`` widget in German, you might use::
locale.setlocale(locale.LC_ALL, 'deu_deu')
:param parent: the parent frame
:param callback: the callable to be executed on selection
:param year: the year as an integer, i.e. `2020`
:param month: the month as an integer; not zero-indexed; i.e.
"1" will translate to "January"
:param day: the day as an integer; not zero-indexed
:param kwargs: tkinter.frame keyword arguments
"""
timedelta = datetime.timedelta
datetime = datetime.datetime
def __init__(
self,
parent,
callback: callable = None,
year: int = None,
month: int = None,
day: int = None,
**kwargs
):
# remove custom options from kw before initializing ttk.Frame
fwday = calendar.SUNDAY
now = self.datetime.now()
year = year if year else now.year
month = month if month else now.month
day = day if day else now.day
locale = kwargs.pop("locale", None)
sel_bg = kwargs.pop("selectbackground", "#ecffc4")
sel_fg = kwargs.pop("selectforeground", "#05640e")
self._date = self.datetime(year, month, day)
self._selection = None # no date selected
self.callback = callback
super().__init__(parent, **kwargs)
self._cal = _get_calendar(locale, fwday)
self.__setup_styles() # creates custom styles
self.__place_widgets() # pack/grid used widgets
self.__config_calendar() # adjust calendar columns and setup tags
# configure a _canvas, and proper bindings, for selecting dates
self.__setup_selection(sel_bg, sel_fg)
# store items ids, used for insertion later
self._items = [self._calendar.insert("", "end", values="") for _ in range(6)]
# insert dates in the currently empty calendar
self._build_calendar()
def __setitem__(self, item, value):
if item in ("year", "month"):
raise AttributeError("attribute '%s' is not writeable" % item)
elif item == "selectbackground":
self._canvas["background"] = value
elif item == "selectforeground":
self._canvas.itemconfigure(self._canvas.text, item=value)
else:
ttk.Frame.__setitem__(self, item, value)
def __getitem__(self, item):
if item in ("year", "month"):
return getattr(self._date, item)
elif item == "selectbackground":
return self._canvas["background"]
elif item == "selectforeground":
return self._canvas.itemcget(self._canvas.text, "fill")
else:
r = ttk.tclobjs_to_py({item: ttk.Frame.__getitem__(self, item)})
return r[item]
def __setup_styles(self):
# custom ttk styles
style = ttk.Style(self.master)
def arrow_layout(dir):
return [("Button.focus", {"children": [("Button.%sarrow" % dir, None)]})]
style.layout("L.TButton", arrow_layout("left"))
style.layout("R.TButton", arrow_layout("right"))
def __place_widgets(self):
# header frame and its widgets
hframe = ttk.Frame(self)
lbtn = ttk.Button(hframe, style="L.TButton", command=self._prev_month)
rbtn = ttk.Button(hframe, style="R.TButton", command=self._next_month)
self._header = ttk.Label(hframe, width=15, anchor="center")
# the calendar
self._calendar = ttk.Treeview(self, show="", selectmode="none", height=7)
# pack the widgets
hframe.pack(in_=self, side="top", pady=4, anchor="center")
lbtn.grid(in_=hframe)
self._header.grid(in_=hframe, column=1, row=0, padx=12)
rbtn.grid(in_=hframe, column=2, row=0)
self._calendar.pack(in_=self, expand=1, fill="both", side="bottom")
def __config_calendar(self):
cols = self._cal.formatweekheader(3).split()
self._calendar["columns"] = cols
self._calendar.tag_configure("header", background="grey90")
self._calendar.insert("", "end", values=cols, tag="header")
# adjust its columns width
font = Font()
maxwidth = max(font.measure(col) for col in cols)
for col in cols:
self._calendar.column(col, width=maxwidth, minwidth=maxwidth, anchor="e")
def __setup_selection(self, sel_bg, sel_fg):
self._font = Font()
self._canvas = canvas = tk.Canvas(
self._calendar, background=sel_bg, borderwidth=0, highlightthickness=0
)
canvas.text = canvas.create_text(0, 0, fill=sel_fg, anchor="w")
canvas.bind("<ButtonPress-1>", lambda evt: canvas.place_forget())
self._calendar.bind("<Configure>", lambda evt: canvas.place_forget())
self._calendar.bind("<ButtonPress-1>", self._pressed)
def __minsize(self, evt):
width, height = self._calendar.master.geometry().split("x")
height = height[: height.index("+")]
self._calendar.master.minsize(width, height)
def _build_calendar(self):
year, month = self._date.year, self._date.month
# update header text (Month, YEAR)
header = self._cal.formatmonthname(year, month, 0)
self._header["text"] = header.title()
# update calendar shown dates
cal = self._cal.monthdayscalendar(year, month)
for indx, item in enumerate(self._items):
week = cal[indx] if indx < len(cal) else []
fmt_week = [("%02d" % day) if day else "" for day in week]
self._calendar.item(item, values=fmt_week)
def _show_selection(self, text, bbox):
"""
Configure canvas for a new selection.
"""
x, y, width, height = bbox
textw = self._font.measure(text)
canvas = self._canvas
canvas.configure(width=width, height=height)
canvas.coords(canvas.text, width - textw, height / 2 - 1)
canvas.itemconfigure(canvas.text, text=text)
canvas.place(in_=self._calendar, x=x, y=y)
# Callbacks
def _pressed(self, evt):
"""
Clicked somewhere in the calendar.
"""
x, y, widget = evt.x, evt.y, evt.widget
item = widget.identify_row(y)
column = widget.identify_column(x)
if not column or item not in self._items:
# clicked in the weekdays row or just outside the columns
return
item_values = widget.item(item)["values"]
if not len(item_values): # row is empty for this month
return
text = item_values[int(column[1]) - 1]
if not text: # date is empty
return
bbox = widget.bbox(item, column)
if not bbox: # calendar not visible yet
return
# update and then show selection
text = "%02d" % text
self._selection = (text, item, column)
self._show_selection(text, bbox)
if self.callback is not None:
self.callback()
def add_callback(self, callback: callable):
"""
Adds a callback to call when the user clicks on a date
:param callback: a callable function
:return: None
"""
self.callback = callback
def _prev_month(self):
"""
Updated calendar to show the previous month.
"""
self._canvas.place_forget()
self._date = self._date - self.timedelta(days=1)
self._date = self.datetime(self._date.year, self._date.month, 1)
self._build_calendar() # reconstruct calendar
def _next_month(self):
"""
Update calendar to show the next month.
"""
self._canvas.place_forget()
year, month = self._date.year, self._date.month
self._date = self._date + self.timedelta(
days=calendar.monthrange(year, month)[1] + 1
)
self._date = self.datetime(self._date.year, self._date.month, 1)
self._build_calendar() # reconstruct calendar
@property
def selection(self):
"""
Return a datetime representing the current selected date.
"""
if not self._selection:
return None
year, month = self._date.year, self._date.month
return self.datetime(year, month, int(self._selection[0]))
class _SlotFrame(ttk.Frame):
"""A single slot"""
def __init__(self, parent, remove_callback=None, entries=1):
self.parent = parent
super().__init__(self.parent)
self.columnconfigure(0, weight=1)
self._entries = []
if entries < 1:
raise ValueError("entries must be >= 1")
for i in range(entries):
entry = ttk.Entry(self)
entry.grid(row=0, column=i, sticky="ew")
self._entries.append(entry)
self._image = tk.PhotoImage(data=minus).subsample(2, 2)
self._remove_btn = ttk.Button(self, image=self._image, command=self.remove)
self._remove_btn.grid(row=0, column=entries, sticky="ew")
self.deleted = False
self._remove_callback = remove_callback
def add(self, string: (str, list)):
"""
Clear the contents of the entry field and
insert the contents of string.
:param string: an str containing the text to display
:return:
"""
if len(self._entries) == 1:
self._entries[0].delete(0, "end")
self._entries[0].insert(0, string)
else:
if len(string) != len(self._entries):
raise ValueError(
'the "string" list must be ' "equal to the number of entries"
)
for i, e in enumerate(self._entries):
self._entries[i].delete(0, "end")
self._entries[i].insert(0, string[i])
def remove(self):
"""
Deletes itself.
:return: None
"""
for e in self._entries:
e.grid_forget()
e.destroy()
self._remove_btn.grid_forget()
self._remove_btn.destroy()
self.deleted = True
if self._remove_callback:
self._remove_callback()
def get(self):
"""
Returns the value for the slot.
:return: the entry value
"""
values = [e.get() for e in self._entries]
if len(self._entries) == 1:
return values[0]
else:
return values
class MultiSlotFrame(ttk.Frame):
"""
Can hold several removable elements,
such as a list of files, directories,
or a checklist.::
# create and grid the frame
msf = tk_tools.MultiSlotFrame(root)
msf.grid()
# add some items
msf.add('item 1')
msf.add('item 2')
# get any user-entered or modified values
print(msf.get())
:param parent: the tk parent frame
:param columns: the number of user columns (defaults to 1)
"""
def __init__(self, parent, columns: int = 1):
self._parent = parent
super().__init__(self._parent)
self.columnconfigure(0, weight=1)
self._slot_columns = columns
self._slots = []
self._blank_label = None
self._redraw()
self._blank_label = ttk.Label(self, text="<no data>")
self._blank_label.grid(row=0, column=0)
def _redraw(self):
"""
Clears the current layout and re-draws all elements in self._slots
:return:
"""
if self._blank_label:
self._blank_label.grid_forget()
self._blank_label.destroy()
self._blank_label = None
for slot in self._slots:
slot.grid_forget()
self._slots = [slot for slot in self._slots if not slot.deleted]
max_per_col = 8
for i, slot in enumerate(self._slots):
slot.grid(row=i % max_per_col, column=int(i / max_per_col), sticky="ew")
def add(self, string: (str, list)):
"""
Add a new slot to the multi-frame containing the string.
:param string: a string to insert
:return: None
"""
slot = _SlotFrame(
self, remove_callback=self._redraw, entries=self._slot_columns
)
slot.add(string)
self._slots.append(slot)
self._redraw()
def clear(self):
"""
Clear out the multi-frame
:return:
"""
for slot in self._slots:
slot.grid_forget()
slot.destroy()
self._slots = []
def get(self):
"""
Retrieve and return the values in the multi-frame
:return: A list of values containing the contents of the GUI
"""
return [slot.get() for slot in self._slots]
class SevenSegment(tk.Frame):
"""
Creates a single seven-segment display which may be
used to emulate a numeric display of old::
# create and grid the frame
ss = tk_tools.SevenSegment(root)
ss.grid()
# set the value
ss.set_value(2)
# set the value with a period
ss.set_value(6.0)
:param parent: the tk parent frame
:param height: the widget height (defaults to 50)
:param digit_color: the digit color (ex: 'black', '#ff0000')
:param background: the background color (ex: 'black', '#ff0000')
"""
def __init__(
self, parent, height: int = 50, digit_color="black", background="white"
):
self._parent = parent
self._color = digit_color
self._bg_color = background
super().__init__(
self._parent,
height=height,
width=int(height / 2),
background=self._bg_color,
)
self.columnconfigure(0, weight=1)
self.columnconfigure(1, weight=1)
self.columnconfigure(2, weight=8)
self.columnconfigure(3, weight=1)
self.columnconfigure(4, weight=1)
self.rowconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
self.rowconfigure(2, weight=8)
self.rowconfigure(3, weight=1)
self.rowconfigure(4, weight=8)
self.rowconfigure(5, weight=1)
self._segments = dict()
self._segments["a"] = tk.Frame(self, bg=self._bg_color)
self._segments["a"].grid(row=1, column=2, sticky="news")
self._segments["b"] = tk.Frame(self, bg=self._bg_color)
self._segments["b"].grid(row=2, column=3, sticky="news")
self._segments["c"] = tk.Frame(self, bg=self._bg_color)
self._segments["c"].grid(row=4, column=3, sticky="news")
self._segments["d"] = tk.Frame(self, bg=self._bg_color)
self._segments["d"].grid(row=5, column=2, sticky="news")
self._segments["e"] = tk.Frame(self, bg=self._bg_color)
self._segments["e"].grid(row=4, column=1, sticky="news")
self._segments["f"] = tk.Frame(self, bg=self._bg_color)
self._segments["f"].grid(row=2, column=1, sticky="news")
self._segments["g"] = tk.Frame(self, bg=self._bg_color)
self._segments["g"].grid(row=3, column=2, sticky="news")
self._segments["period"] = tk.Frame(self, bg=self._bg_color)
self._segments["period"].grid(row=5, column=4, sticky="news")
self.grid_propagate(0)
def clear(self):
"""
Clear the segment.
:return: None
"""
for _, frame in self._segments.items():
frame.configure(background=self._bg_color)
def set_value(self, value: str):
"""
Sets the value of the 7-segment display
:param value: the desired value