-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtkyamlgui.py
1686 lines (1531 loc) · 71.9 KB
/
tkyamlgui.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
import numpy as np
import matplotlib
try:
matplotlib.use('TkAgg')
except:
pass
# For help see:
# https://matplotlib.org/stable/gallery/user_interfaces/embedding_in_tk_sgskip.html
# https://stackoverflow.com/questions/59536002/how-do-i-align-something-to-the-bottom-left-in-tkinter-using-either-grid-or
# https://www.delftstack.com/howto/python-tkinter/how-to-pass-arguments-to-tkinter-button-command/
#
# For tabs with widgets
# https://www.geeksforgeeks.org/creating-tabbed-widget-with-python-tkinter/
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
# implement the default mpl key bindings
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
from functools import partial
from collections import OrderedDict
import sys, os, re
from enum import Enum
if sys.version_info[0] < 3:
import Tkinter as Tk
import ttk
import tkFileDialog as filedialog
import collections as collectionsabc
import ScrolledText as scrolledtext
else:
import tkinter as Tk
from tkinter import ttk
from tkinter import filedialog as filedialog
import collections.abc as collectionsabc
import tkinter.scrolledtext as scrolledtext
# Load NavigationToolbar2TkAgg
try:
# For newer matplotlibs
from matplotlib.backends.backend_tkagg import NavigationToolbar2Tk as NavigationToolbar2TkAgg
except:
# For older matplotlibs
from matplotlib.backends.backend_tkagg import NavigationToolbar2TkAgg
try:
import ruamel.yaml as yaml
#print("# Loaded ruamel.yaml")
useruemel=True
import warnings
warnings.simplefilter('ignore', ruamel.yaml.error.UnsafeLoaderWarning)
try:
yaml = yaml.YAML()
except:
pass
except:
import yaml as yaml
#print("# Loaded yaml")
useruemel=False
#if useruemel: yaml = yaml.YAML()
# Helpful function for pulling things out of dicts
getdictval = lambda d, key, default: default if key not in d else d[key]
# Function to evaluate the string escapes
escapestr = lambda s: s.decode('string_escape') if sys.version_info[0] < 3 else bytes(s, "utf-8").decode("unicode_escape")
verbose = False
# Add some additional input types
class moretypes(Enum):
mergedboollist = 1
listbox = 2
filename = 3
textbox = 4
# Map some strings to types
typemap={}
typemap['str'] = str
typemap['bool'] = bool
typemap['int'] = int
typemap['float'] = float
typemap['mergedboollist'] = moretypes.mergedboollist
typemap['listbox'] = moretypes.listbox
typemap['filename'] = moretypes.filename
typemap['textbox'] = moretypes.textbox
def to_bool(bool_str):
"""Parse the string and return the boolean value encoded or raise an
exception
"""
#if isinstance(bool_str, basestring) and bool_str:
if isinstance(bool_str, str):
if bool_str.lower() in ['true', 't', '1']:
return True
elif bool_str.lower() in ['false', 'f', '0']:
return False
#if here we couldn't parse it
raise ValueError("[%s] is not recognized as a boolean value" % bool_str)
class ToggledFrame(Tk.Frame):
"""
Create a toggled/expandable frame
"""
# See https://stackoverflow.com/questions/13141259/expandable-and-contracting-frame-in-tkinter
def __init__(self, parent, text="", initstate=1, *args, **options):
Tk.Frame.__init__(self, parent, *args, **options)
self.show = Tk.IntVar()
self.show.set(initstate)
self.title_frame = ttk.LabelFrame(parent) #ttk.Frame(self)
self.header_frame = Tk.Frame(self.title_frame)
self.header_frame.grid(row=0, column=0, sticky='w')
defaultwidth=20
w=max(len(text)+2, defaultwidth)
ttk.Label(self.header_frame, text=" "+text, width=w).grid(row=0,
column=1,
sticky='w')
self.toggle_button = ttk.Checkbutton(self.header_frame, width=5,
text='[show]',
command=self.toggle,
variable=self.show,
style='Demo.TButton')
self.toggle_button.grid(row=0, column=0)
self.sub_frame = Tk.Frame(self.title_frame, #relief="sunken",
borderwidth=1)
self.toggle()
def toggle(self):
if bool(self.show.get()):
self.sub_frame.grid(row=1)
self.toggle_button.configure(text='[hide]')
else:
self.sub_frame.grid_forget()
self.toggle_button.configure(text='[show]')
def setstate(self, state):
self.show.set(state)
self.toggle()
class VerticalScrolledFrame:
"""
A vertically scrolled Frame that can be treated like any other Frame
ie it needs a master and layout and it can be a master.
:width:, :height:, :bg: are passed to the underlying Canvas
:bg: and all other keyword arguments are passed to the inner Frame
note that a widget layed out in this frame will have a self.master 3 layers deep,
(outer Frame, Canvas, inner Frame) so
if you subclass this there is no built in way for the children to access it.
You need to provide the controller separately.
"""
# See https://gist.github.com/novel-yet-trivial/3eddfce704db3082e38c84664fc1fdf8
def __init__(self, master, extraconfigfunc=None, **kwargs):
width = kwargs.pop('width', None)
height = kwargs.pop('height', None)
bg = kwargs.pop('bg', kwargs.pop('background', None))
self.outer = Tk.Frame(master, **kwargs)
self.extraconfigfunc = extraconfigfunc;
self.vsb = Tk.Scrollbar(self.outer, orient=Tk.VERTICAL)
self.vsb.pack(fill=Tk.Y, side=Tk.RIGHT)
self.canvas = Tk.Canvas(self.outer, highlightthickness=0, width=width, height=height, bg=bg)
self.canvas.pack(side=Tk.LEFT, fill=Tk.BOTH, expand=True)
self.canvas['yscrollcommand'] = self.vsb.set
# mouse scroll does not seem to work with just "bind"; You have
# to use "bind_all". Therefore to use multiple windows you have
# to bind_all in the current widget
self.canvas.bind("<Enter>", self._bind_mouse)
self.canvas.bind("<Leave>", self._unbind_mouse)
self.vsb['command'] = self.canvas.yview
self.inner = Tk.Frame(self.canvas, bg=bg)
# pack the inner Frame into the Canvas with the topleft corner 4 pixels offset
self.canvas.create_window(4, 4, window=self.inner, anchor='nw')
self.inner.bind("<Configure>", self._on_frame_configure)
self.outer_attr = set(dir(Tk.Widget))
def __getattr__(self, item):
if item in self.outer_attr:
# geometry attributes etc (eg pack, destroy, tkraise) are passed on to self.outer
return getattr(self.outer, item)
else:
# all other attributes (_w, children, etc) are passed to self.inner
return getattr(self.inner, item)
def _on_frame_configure(self, event=None):
x1, y1, x2, y2 = self.canvas.bbox("all")
height = self.canvas.winfo_height()
try:
self.canvas.config(scrollregion = (0,0, x2, max(y2, height)))
if self.extraconfigfunc is not None:
self.extraconfigfunc()
except:
pass
def _bind_mouse(self, event=None):
self.canvas.bind_all("<4>", self._on_mousewheel)
self.canvas.bind_all("<5>", self._on_mousewheel)
self.canvas.bind_all("<MouseWheel>", self._on_mousewheel)
def _unbind_mouse(self, event=None):
self.canvas.unbind_all("<4>")
self.canvas.unbind_all("<5>")
self.canvas.unbind_all("<MouseWheel>")
def _on_mousewheel(self, event):
"""Linux uses event.num; Windows / Mac uses event.delta"""
if event.num == 4 or event.delta > 0:
self.canvas.yview_scroll(-1, "units" )
elif event.num == 5 or event.delta < 0:
self.canvas.yview_scroll(1, "units" )
def __str__(self):
return str(self.outer)
#
# See https://stackoverflow.com/questions/58045626/scrollbar-in-tkinter-notebook-frames
class YScrolledFrame(Tk.Frame, object):
def __init__(self, parent, canvaswidth=500,canvasheight=500,*args,**kwargs):
super(YScrolledFrame, self).__init__(parent, *args, **kwargs)
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
self.canvas = canvas = Tk.Canvas(self, relief='raised',
width=canvaswidth, height=canvasheight)
canvas.grid(row=0, column=0, sticky='nsew')
scroll = Tk.Scrollbar(self, command=canvas.yview, orient=Tk.VERTICAL)
canvas.config(yscrollcommand=scroll.set)
scroll.grid(row=0, column=1, sticky='nsew')
self.yscroll = scroll
self.content = Tk.Frame(canvas)
self.window = self.canvas.create_window(0, 0, window=self.content, anchor="nw")
self.canvas.bind('<Configure>', self.on_configure)
self.content.bind('<Configure>', self.reset_scrollregion)
def on_configure(self, event):
bbox = self.content.bbox('ALL')
self.canvas.config(scrollregion=bbox)
def reset_scrollregion(self, event):
self.canvas.configure(scrollregion=self.canvas.bbox('all'))
def onCanvasConfigure(self, event):
#Resize the inner frame to match the canvas
minWidth = self.content.winfo_reqwidth()
minHeight = self.content.winfo_reqheight()
newWidth = self.winfo_width()
newHeight = event.height
#self.canvas.itemconfig(self.window, height=minHeight)
self.config(width=newWidth, height=newHeight)
bbox = self.content.bbox('ALL')
self.canvas.config(scrollregion=bbox)
class Notebook(ttk.Notebook, object):
def __init__(self, parent, tab_labels, canvaswidth=500, canvasheight=500):
super(Notebook, self).__init__(parent)
self._tab = {}
for text in tab_labels:
#self._tab[text] = YScrolledFrame(self, canvaswidth=canvaswidth)
self._tab[text] = VerticalScrolledFrame(self,
width=canvaswidth,
height=canvasheight)
self._tab[text].pack(fill=Tk.BOTH, expand=True)
# layout by .add defaults to fill=Tk.BOTH, expand=True
self.add(self._tab[text], text=text, compound=Tk.TOP)
def tab(self, key):
return self._tab[key] #.content
def tkextractval(inputtype, tkvar, tkentry, optionlist=[]):
if inputtype is bool:
val = bool(tkvar.get())
elif (inputtype is moretypes.textbox):
val = str(tkentry.get("1.0", 'end-1c'))
elif (inputtype is str) and len(optionlist)>0:
val = str(tkvar.get())
elif (inputtype is moretypes.listbox):
val = [tkentry.get(idx) for idx in tkentry.curselection()]
elif (inputtype is str):
val = str(tkentry.get())
elif (inputtype is moretypes.filename):
val = str(tkentry.get())
elif (inputtype is int):
val = int(float(tkentry.get()))
else: # float
val = float(tkentry.get())
return val
class ToolTip(object):
"""
Creates a mouse-over tool tip show additional context
"""
# See https://stackoverflow.com/questions/20399243/display-message-when-hovering-over-something-with-mouse-cursor-in-python
def __init__(self, widget):
self.widget = widget
self.tipwindow = None
self.id = None
self.x = self.y = 0
def showtip(self, text):
"Display text in tooltip window"
self.text = text
if self.tipwindow or not self.text:
return
x, y, cx, cy = self.widget.bbox("insert")
x = x + self.widget.winfo_rootx() + 57
y = y + cy + self.widget.winfo_rooty() +27
self.tipwindow = tw = Tk.Toplevel(self.widget)
tw.wm_overrideredirect(1)
tw.wm_geometry("+%d+%d" % (x, y))
label = Tk.Label(tw, text=self.text, justify=Tk.LEFT,
background="#ffffe0", relief=Tk.SOLID, borderwidth=1,
font=("tahoma", "8", "normal"))
label.pack(ipadx=1)
def hidetip(self):
tw = self.tipwindow
self.tipwindow = None
if tw:
tw.destroy()
def CreateToolTip(widget, text):
"""
Binds a ToolTip to widget with text
"""
toolTip = ToolTip(widget)
def enter(event):
toolTip.showtip(text)
def leave(event):
toolTip.hidetip()
widget.bind('<Enter>', enter)
widget.bind('<Leave>', leave)
class inputwidget:
"""
Creates a general-purpose widget for input
"""
def __init__(self, frame, row, inputtype, name, label,
parent=None,
defaultval=None, optionlist=[],
listboxopt={}, fileopenopt={},
ctrlframe=None, ctrlelem=None,
labelonly=False, visible=True, entryopt={},
outputdef={}, mergedboollist=[], allinputs=None):
defaultw = 12
self.name = name
self.label = label
self.parent = parent
self.labelonly = labelonly
self.inputtype = inputtype
self.var = None
self.defaultval= defaultval
self.optionlist= optionlist
self.listboxopt= listboxopt
self.ctrlframe = ctrlframe
self.ctrlelem = ctrlelem
self.visible = visible
self.outputdef = outputdef
self.mergedboollist = mergedboollist
self.button = None
self.allinputs = allinputs
if visible:
self.tklabel = Tk.Label(frame, text=label)
else:
self.tklabel = None
if 'width' not in entryopt: entryopt['width'] = defaultw
self.entryopt = entryopt
if inputtype == moretypes.mergedboollist: return
if visible:
cspan=3 if labelonly else 1
if row is None:
self.tklabel.grid(column=0, columnspan=cspan,sticky='nw',padx=5)
else:
self.tklabel.grid(row=row, columnspan=cspan,
column=0, sticky='nw', padx=5)
if 'help' in self.outputdef:
CreateToolTip(self.tklabel, text=self.outputdef['help'])
if labelonly: return None
if inputtype is bool:
# create a checkvar
self.var = Tk.IntVar()
if defaultval is not None: self.var.set(defaultval)
if self.ctrlelem is None:
self.tkentry = Tk.Checkbutton(frame, variable=self.var)
else:
self.tkentry = Tk.Checkbutton(frame, variable=self.var,
command=partial(self.onoffctrlelem, None))
elif (inputtype is moretypes.listbox):
allopts = eval(optionlist) if isinstance(optionlist,str) else optionlist
height=max(3,len(allopts))
if 'height' not in listboxopt: listboxopt['height'] = height
self.yscroll = Tk.Scrollbar(frame, orient=Tk.VERTICAL)
if visible and (row is None): row=self.tklabel.grid_info()['row']
if visible: self.yscroll.grid(row=row, column=2, sticky=Tk.NW+Tk.S)
self.tkentry = Tk.Listbox(frame, #height=height,
exportselection=False,
yscrollcommand=self.yscroll.set,
**listboxopt)
for i, option in enumerate(allopts):
self.tkentry.insert(i+1, option)
self.yscroll['command'] = self.tkentry.yview
# Set the default values
if defaultval is not None:
if not isinstance(defaultval, list): defaultval = [defaultval]
for v in defaultval:
# set the value to active
if v in self.optionlist:
self.tkentry.selection_set(self.optionlist.index(v))
if self.ctrlelem is not None:
self.tkentry.bind("<<ListboxSelect>>", self.onoffctrlelem)
elif (inputtype is str) and (len(optionlist)>0):
# create a dropdown menu
self.var = Tk.StringVar()
optlist = eval(optionlist) if isinstance(optionlist,str) else optionlist
if len(optlist)==0: optlist=['']
self.tkentry = Tk.OptionMenu(frame, self.var, *optlist)
#self.tkentry.config(**self.entryopt)
if defaultval is not None: self.var.set(defaultval)
elif (inputtype is moretypes.textbox):
self.var = Tk.StringVar()
self.tkentry = scrolledtext.ScrolledText(master=frame,
**self.entryopt)
formattedval = escapestr(defaultval)
self.tkentry.insert('1.0', formattedval.strip("'").strip('"'))
elif (inputtype is str):
self.var = Tk.StringVar()
self.tkentry = Tk.Entry(master=frame, **self.entryopt)
self.tkentry.insert(0, repr(defaultval).strip("'").strip('"'))
elif (inputtype is moretypes.filename):
self.var = Tk.StringVar()
self.tkentry = Tk.Entry(master=frame, **self.entryopt)
if defaultval is not None:
self.tkentry.insert(0, repr(defaultval).strip("'").strip('"'))
# Add a button to choose filename
self.button = Tk.Button(master=frame,
text="Choose file",
command=partial(self.choosefile,
fileopenopt))
elif (isinstance(inputtype, list)):
# Handle list inputs
N = len(inputtype)
self.var = []
self.tkentry = []
#varlistlength
self.listN = N if defaultval is None else len(defaultval)
self.varlenlist= entryopt.pop('varlenlist', False)
#self.varlenlist= getdictval(entryopt, 'varlenlist', False)
for i in range(N):
self.var.append(None)
self.tkentry.append(Tk.Entry(master=frame, **self.entryopt))
if defaultval is not None:
if i < len(defaultval): #varlistlength
self.tkentry[i].insert(0, repr(defaultval[i]).strip("'").strip('"'))
else:
self.tkentry = Tk.Entry(master=frame, **self.entryopt)
self.tkentry.insert(0, repr(defaultval).strip("'").strip('"'))
# Add the entry to the frame
if visible:
if row is None: row=self.tklabel.grid_info()['row']
if (isinstance(inputtype, list)):
for i in range(len(inputtype)):
self.tkentry[i].grid(row=row, column=1+i, sticky='w')
else:
self.tkentry.grid(row=row, column=1, sticky='w')
if self.button is not None:
self.button.grid(row=row, column=2, sticky='nw')
return
def getval(self):
"""Return the value"""
try:
if isinstance(self.inputtype, list):
val = []
#for i in range(len(self.inputtype)):
for i in range(self.listN): #varlistlength
try:
ival = tkextractval(self.inputtype[i],
self.var[i],
self.tkentry[i])
val.append(ival)
except:
if not self.varlenlist:
if verbose: print("Insufficient items in "+
self.name)
val = None
else:
continue
elif (self.inputtype == moretypes.mergedboollist):
val = []
for var in self.mergedboollist:
boolvar = var[0]
iftrue = var[1]
iffalse = var[2]
if self.allinputs[boolvar].getval():
val.append(iftrue)
else:
val.append(iffalse)
# Remove all empty values from list
val = [x for x in val if x != '']
if len(val)<1: val = None
else:
# Scalar primitive types
val = tkextractval(self.inputtype, self.var, self.tkentry,
optionlist=self.optionlist)
except:
if verbose: print("getval(): Error in "+self.name)
val = None
return val
def setval(self, val, strinput=False, forcechange=False):
"""Update the contents with val"""
if (isinstance(self.inputtype, list)):
listval=val
if strinput: listval = re.split(r'[,; ]+', val)
if listval is None: return
if (not self.varlenlist) and (len(listval) != len(self.inputtype)):
print("Insufficient number of inputs in list for "+self.name)
return
if self.varlenlist:
self.listN = min(len(listval), len(self.inputtype))
# Clear the list
for i in range(len(self.inputtype)):
itkentry= self.tkentry[i]
itkentry.delete(0, Tk.END)
# Input a list
#for i in range(len(self.inputtype)): #varlistlength
for i in range(self.listN): #varlistlength
itkentry= self.tkentry[i]
statedisabled= itkentry.cget('state') in ['disable','disabled']
if statedisabled and forcechange==False:
print("CANNOT update: %s use forcechange=True in setval()"
%self.name)
if statedisabled and forcechange:
itkentry.config(state='normal')
itkentry.delete(0, Tk.END)
if i < len(listval):
itkentry.insert(0, repr(listval[i]).strip("'").strip('"'))
else:
print("WARNING: cannot set %s entry i=%i"%(self.name, i))
if statedisabled and forcechange: # Reset the state
itkentry.config(state='disabled')
else:
# Check to see if entry is normal or disabled
if self.inputtype==moretypes.mergedboollist:
statedisabled=False
else:
statedisabled=self.tkentry.cget('state') in ['disable','disabled']
if statedisabled and forcechange==False:
print("CANNOT update: %s use forcechange=True in setval()"
%self.name)
if statedisabled and forcechange:
self.tkentry.config(state='normal')
# Handle scalars
if self.inputtype is bool:
boolval = to_bool(val) if strinput else val
#print("Set "+self.name+" to "+repr(val))
self.var.set(boolval)
if self.ctrlelem is not None: self.onoffctrlelem(None)
elif (self.inputtype is str) and len(self.optionlist)>0:
self.var.set(val.strip("'").strip('"'))
elif (self.inputtype is moretypes.textbox):
self.tkentry.delete('1.0', 'end')
self.tkentry.insert('1.0', escapestr(val).strip("'").strip('"'))
elif self.inputtype==moretypes.listbox:
listval = val
if strinput: listval = re.split(r'[,; ]+', val)
self.tkentry.selection_clear(0, Tk.END)
for v in listval:
# set the value to active
allopts = eval(self.optionlist) if isinstance(self.optionlist,str) else self.optionlist
self.tkentry.selection_set(allopts.index(v))
elif self.inputtype==moretypes.mergedboollist:
allboolstrs=[item for sublist in self.mergedboollist for item in sublist[1:]]
listval=val
if strinput: listval = re.split(r'[,; ]+', val)
if '' in allboolstrs:
# Could be in any order
for boolinput in self.mergedboollist:
if boolinput[1] in listval:
self.allinputs[boolinput[0]].setval(True)
else:
self.allinputs[boolinput[0]].setval(False)
else:
# Take it in order
for istr, strinput in enumerate(listval):
boolinput=self.mergedboollist[istr]
if strinput.lower()==boolinput[1].lower():
self.allinputs[boolinput[0]].setval(True)
elif strinput.lower()==boolinput[2].lower():
self.allinputs[boolinput[0]].setval(False)
else:
raise ValueError("%s is not either %s or %s."%(strinput, boolinput[1], boolinput[2]))
else:
# Set a string in the entry
self.tkentry.delete(0, Tk.END)
self.tkentry.insert(0, repr(val).strip("'").strip('"'))
if statedisabled and forcechange: # Reset the state
self.tkentry.config(state='disabled')
return
def setdefault(self):
if self.defaultval is not None:
self.setval(self.defaultval, forcechange=True)
return
def isactive(self):
if self.labelonly: return False
if self.inputtype==moretypes.mergedboollist: return True
if isinstance(self.tkentry, list):
state = self.tkentry[0].cget('state')
else:
state = self.tkentry.cget('state')
isnormalstate = (state=='normal')
hasdata = False
if isnormalstate:
hasdata = (str(self.getval())!='')
return (isnormalstate and hasdata)
def choosefile(self, optiondict):
#filewin = Tk.Toplevel()
selecttype = getdictval(optiondict, 'selecttype', 'open')
kwargs = getdictval(optiondict, 'kwargs', {})
if 'filetypes' in kwargs:
kwargs['filetypes'] = [(g[0], g[1]) for g in kwargs['filetypes']]
if selecttype=='open':
filename = filedialog.askopenfilename(initialdir = "./",
title = "Select file",
**kwargs)
elif selecttype=='saveas':
filename = filedialog.asksaveasfilename(initialdir = "./",
title = "Select file",
**kwargs)
elif selecttype=='directory':
filename = filedialog.askdirectory(initialdir = "./",
title = "Select directory",
**kwargs)
self.tkentry.delete(0, Tk.END)
self.tkentry.insert(0, filename)
return filename
def refresh_listbox(self, refreshlist):
"""
Repopulate the listbox options from refreshlist
"""
if self.inputtype != moretypes.listbox:
print("refresh_listbox ERROR: %s is not listbox"%self.name)
return
# Delete and repopulate it
self.tkentry.delete(0, Tk.END)
for i, option in enumerate(refreshlist):
self.tkentry.insert(i+1, option)
return
# DELETE THIS! OBSOLETE!
def onoffframe(self):
if self.var.get() == 1:
for child in self.ctrlframe.winfo_children():
child.configure(state='normal')
else:
for child in self.ctrlframe.winfo_children():
child.configure(state='disable')
return
def onoffctrlelem(self, event):
currstate = self.getval()
# Handle the bool option first
if self.inputtype is bool:
for ielem, elem in enumerate(self.ctrlelem):
if 'activewhen' in elem:
criteria = elem['activewhen']
condition = criteria[1]
else:
condition = True
if bool(currstate)==bool(condition):
framestate, inputstate = 'normal', 'normal'
else:
framestate, inputstate = 'disable', 'disabled'
if elem['ctrlframe'] is not None:
#print("Set "+elem['frame']+" to "+framestate)
for child in elem['ctrlframe'].winfo_children():
try: child.configure(state=framestate)
except: None
if elem['ctrlinput'] is not None:
#print("Set "+elem['input']+" to "+inputstate)
if isinstance(elem['ctrlinput'].tkentry, list):
for entry in elem['ctrlinput'].tkentry:
try: entry.config(state=inputstate)
except: None
else:
try: elem['ctrlinput'].tkentry.config(state=inputstate)
except: None
# Handle the str type
if self.inputtype == str:
for ielem, elem in enumerate(self.ctrlelem):
criteria = elem['activewhen']
optiontest= criteria[0]
condition = criteria[1]
if currstate==condition:
framestate, inputstate = 'normal', 'normal'
else:
framestate, inputstate = 'disable', 'disabled'
if elem['ctrlframe'] is not None:
#print("Set "+elem['frame']+" to "+framestate)
for child in elem['ctrlframe'].winfo_children():
try: child.configure(state=framestate)
except: None
if elem['ctrlinput'] is not None:
#print("Set "+elem['input']+" to "+inputstate)
if isinstance(elem['ctrlinput'].tkentry, list):
for entry in elem['ctrlinput'].tkentry:
try: entry.config(state=inputstate)
except: None
else:
try: elem['ctrlinput'].tkentry.config(state=inputstate)
except: None
# Handle the listbox option
if self.inputtype == moretypes.listbox:
# Get the current state
#print("curr state = "+repr(currstate))
for ielem, elem in enumerate(self.ctrlelem):
criteria = elem['activewhen']
optiontest= criteria[0]
condition = criteria[1]
#print("testing "+optiontest+" "+repr(condition))
if (optiontest in currstate) == bool(condition):
# Passes test, let's activate/deactivate
framestate, inputstate = 'normal', 'normal'
else:
framestate, inputstate = 'disable', 'disabled'
if elem['ctrlframe'] is not None:
#print("Set "+elem['frame']+" to "+framestate)
for child in elem['ctrlframe'].winfo_children():
try: child.configure(state=framestate)
except: None
if elem['ctrlinput'] is not None:
#print("Set "+elem['input']+" to "+inputstate)
if isinstance(elem['ctrlinput'].tkentry, list):
for entry in elem['ctrlinput'].tkentry:
try:
entry.config(state=inputstate)
except:
None
else:
try: elem['ctrlinput'].tkentry.config(state=inputstate)
except: None
return
def linkctrlelem(self, allframes, allinputs):
"""
Link the ctrl elements to the frames/inputs to control
"""
for ielem, elem in enumerate(self.ctrlelem):
#print(self.name)
# Attach it to the right thing
if 'frame' in elem:
self.ctrlelem[ielem]['ctrlframe'] = allframes[elem['frame']]
self.ctrlelem[ielem]['ctrlinput'] = None
elif 'input' in elem:
self.ctrlelem[ielem]['ctrlframe'] = None
self.ctrlelem[ielem]['ctrlinput'] = allinputs[elem['input']]
else:
print("Invalid ctrlelem specification in "+self.name)
return
@classmethod
def fromdict(cls, frame, d, parent=None, allframes=None, allinputs=None):
# Parse the dict
name = d['name']
row = getdictval(d, 'row', None)
label = getdictval(d, 'label', '')
defaultval = getdictval(d, 'defaultval', None)
optionlist = getdictval(d, 'optionlist', [])
labelonly = getdictval(d, 'labelonly', False)
visible = getdictval(d, 'visible', True)
# Set the control frame (for booleans)
ctrlframe = None
if ('ctrlframe' in d) and (allframes is not None):
ctrlframe = allframes[d['ctrlframe']]
ctrlelem = getdictval(d, 'ctrlelem', None)
yamlinputtype = getdictval(d, 'inputtype', 'str')
if isinstance(yamlinputtype, list):
inputtype = [typemap[x.lower()] for x in yamlinputtype]
else:
inputtype = typemap[yamlinputtype.lower()]
mergedboollist = getdictval(d, 'mergedboollist', [])
outputdef = getdictval(d, 'outputdef', {})
listboxopt = getdictval(d, 'listboxopt', {})
fileopenopt= getdictval(d, 'fileopenopt', {})
entryopt = getdictval(d, 'entryopt', {})
# Return the widget
return cls(frame, row, inputtype, name, label, parent=parent,
defaultval=defaultval, optionlist=optionlist,
listboxopt=listboxopt, fileopenopt=fileopenopt,
ctrlframe=ctrlframe, ctrlelem=ctrlelem,
labelonly=labelonly, entryopt=entryopt,
outputdef=outputdef, mergedboollist=mergedboollist,
allinputs=allinputs, visible=visible)
# -- Done inputwidget --
class popupwindow(Tk.Toplevel, object):
"""
Creates a pop-up window
"""
def __init__(self, parent, master, defdict, stored_inputvars,
extraclosefunc=None, savebutton=True,
savebtxt='Save', closebtxt='Close', entrynum=None,
quitafterinit=False, popupgui=True, hidden=False):
self.scrollframe=scrollframe=True
if popupgui:
super(popupwindow, self).__init__(parent)
if 'title' in defdict: self.wm_title(defdict['title'])
if scrollframe:
width = getdictval(defdict, 'width', 500)
height = getdictval(defdict, 'height', 500)
self.scrolledframe = VerticalScrolledFrame(self,
width=width,
height=height)
self.scrolledframe.pack(fill=Tk.BOTH, expand=True) # fill window
self.parent = parent
self.master = master
self.extraclosefunc = extraclosefunc
self.datakeyname = getdictval(defdict, 'datakeyname', None)
self.stored_inputvars=stored_inputvars
self.drawframe = self
if scrollframe and popupgui:
self.drawframe = self.scrolledframe
# Initialize the values if stored_inputvars is empty
if not stored_inputvars:
for widget in defdict['inputwidgets']:
if getdictval(widget, 'labelonly', False) == False:
self.stored_inputvars[widget['name']] = widget['defaultval']
if quitafterinit: return
if popupgui==False: print("Initiating no gui")
if hidden: self.withdraw()
# Add some frames to the pop-up window
self.popup_subframes = OrderedDict()
self.popup_toggledframes = OrderedDict()
if 'frames' in defdict:
for frame in defdict['frames']:
toggled = True if (('toggled' in frame) and frame['toggled']) else False
name = frame['name']
drawframe = self.popup_subframes[frame['frame']] if 'frame' in frame else self.drawframe
kwargs = {} if 'kwargs' not in frame else frame['kwargs']
if toggled:
title = '' if ('title' not in frame) else frame['title']
state = 0 if ('initstate' not in frame) else frame['initstate']
self.popup_toggledframes[name] = ToggledFrame(drawframe,
text=title,
relief="raised",
initstate=state,
borderwidth=1)
self.popup_subframes[name] = self.popup_toggledframes[name].sub_frame
subframelayout = self.popup_toggledframes[name].title_frame
else:
self.popup_subframes[name] = Tk.LabelFrame(drawframe, **kwargs)
subframelayout = self.popup_subframes[name]
# Put frame on grid
kwargs = {}
if 'row' in frame: kwargs['row'] = frame['row']
col = 0 if 'col' not in frame else frame['col']
subframelayout.grid(column=col, padx=10,pady=10,
columnspan=4, sticky='w',
**kwargs)
if ('title' in frame) and (not toggled):
Tk.Label(self.popup_subframes[name],
text=frame['title']).grid(row=0, column=col,
columnspan=4,
sticky='w')
# populate the window
self.temp_inputvars = OrderedDict()
for widget in defdict['inputwidgets']:
widgetcopy = widget.copy()
name = widgetcopy['name']
#widgetcopy['visible'] = popupgui
if getdictval(widget, 'labelonly', False) is False:
widgetcopy['defaultval'] = self.stored_inputvars[name]
widgetframe = getdictval(widget, 'frame', None)
targetframe = self.drawframe if widgetframe is None else self.popup_subframes[widgetframe]
if 'optionlist' in widgetcopy:
if isinstance(widgetcopy['optionlist'], str):
widgetcopy['optionlist'] = eval(widgetcopy['optionlist'])
iwidget = inputwidget.fromdict(targetframe,
widgetcopy, parent=parent,
allinputs=self.temp_inputvars)
self.temp_inputvars[name] = iwidget
# link any widgets necessary
for key, inputvar in self.temp_inputvars.items():
if self.temp_inputvars[key].ctrlelem is not None:
self.temp_inputvars[key].linkctrlelem(self.popup_subframes,
self.temp_inputvars)
self.temp_inputvars[key].onoffctrlelem(None)
# Append an entry number to name (if necessary)
if entrynum is not None:
name=self.temp_inputvars[self.datakeyname].getval()
self.temp_inputvars[self.datakeyname].setval(name+repr(entrynum))
if popupgui:
# -- Set up the buttons --
Nbuttons = 0
if 'buttons' in defdict:
Nbuttons = len(defdict['buttons'])
for button in defdict['buttons']:
text = button['text']
cmdstr= button['command']
col = getdictval(button, 'col', 0)
widgetframe = getdictval(button, 'frame', None)
targetframe = self.drawframe if widgetframe is None else self.popup_subframes[widgetframe]
b = Tk.Button(master=targetframe, #self.drawframe,
text=text,command=eval(cmdstr))
if 'row' in button:
b.grid(row=button['row'], column=col,padx=5,sticky='w')
else:
b.grid(column=col, padx=5, sticky='w')
# Add the save button
row = len(defdict['inputwidgets'])+Nbuttons+1 #row+3
col=0
if savebutton:
Tk.Button(self.drawframe,
text=savebtxt,command=self.savevals).grid(row=row, column=0)
col=1
# Add the close button
Tk.Button(self.drawframe,
text=closebtxt, command=self.okclose).grid(row=row, column=col)
# col_count, row_count = self.drawframe.grid_size()
# for n in range(row_count):
# self.drawframe.grid_rowconfigure(n, minsize=25, weight=1)
for key, frame in self.popup_subframes.items():
col_count, row_count = frame.grid_size()
#print('key = %s col = %i row = %i'%(key, col_count, row_count))
for n in range(row_count):
frame.grid_rowconfigure(n, minsize=15, weight=1)
return
def savevals(self):
for key, widget in self.stored_inputvars.items():
val = self.temp_inputvars[key].getval()
self.stored_inputvars[key] = val
if self.datakeyname is not None:
return self.stored_inputvars[self.datakeyname]
else:
return None
def okclose(self):
dataname=self.savevals()
if self.extraclosefunc is not None:
# Call this function to validate data or other stuff
self.extraclosefunc()
self.destroy()
def printvals(self):
for key, widget in self.stored_inputvars.items():
val = self.stored_inputvars[key]
print(key+" "+repr(val))
return
def savethenexec(self, cmdstr):
self.savevals()
exec(cmdstr)
return
def updatelistbox(self, listbox, listboxpopuptarget):
newlist = self.parent.refresh_popupwindow_listbox(listboxpopuptarget)
self.temp_inputvars[listbox].refresh_listbox(newlist)
return
# -- Done popupwindow --