forked from onp/gmcr-py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
widgets_f02a_01_radioButtonEntry.py
234 lines (180 loc) · 8.51 KB
/
widgets_f02a_01_radioButtonEntry.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
# Copyright: (c) Oskar Petersons 2013
"""Widgets for selecting a state using radio buttons for each option.
Loaded by the frame_02a_misperceptions module.
Copied from a very similar widget used on the infeasibles screen.
"""
from tkinter import Tk, Canvas, N, S, E, W, VERTICAL, StringVar
from tkinter import ttk
from data_01_conflictModel import ConflictModel
NSEW = (N, S, E, W)
class RadiobuttonSeries(ttk.Labelframe):
"""State entry for a single decision maker."""
def __init__(self, master=None, text=None, width=None, *args):
"""Initialize the widget."""
ttk.Labelframe.__init__(self, master, text=text, width=width, *args)
self.columnconfigure(0, weight=1)
self.options = []
self.stringVarList = []
self.yLabel = ttk.Label(self, text='Y ', anchor="w")
self.nLabel = ttk.Label(self, text='N ', anchor="w")
self.oLabel = ttk.Label(self, text='Open', anchor="w")
self.yLabel.grid(column=1, row=0)
self.nLabel.grid(column=2, row=0)
self.oLabel.grid(column=3, row=0)
self.placeholder = False
self.setOpts(self.options)
def setOpts(self, options, *args):
"""Create Radiobutton inputs for each Option for the target DM."""
if not options:
self.placeholder = ttk.Label(self, text="This DM has no Options.")
self.placeholder.grid(column=0, row=1, columnspan=4, sticky=NSEW)
return None
if self.placeholder:
self.placeholder.grid_forget()
self.options = options
self.stringVarList = []
for idx, opt in enumerate(self.options):
self.stringVarList.append(StringVar(value='-'))
yb = ttk.Radiobutton(self, variable=self.stringVarList[idx],
value='Y', command=self.chgEvent)
nb = ttk.Radiobutton(self, variable=self.stringVarList[idx],
value='N', command=self.chgEvent)
ob = ttk.Radiobutton(self, variable=self.stringVarList[idx],
value='-', command=self.chgEvent)
name = ttk.Label(self, text=opt.name)
yb.grid(column=1, row=int(idx + 1), padx=(15, 10), pady=5)
nb.grid(column=2, row=int(idx + 1), padx=(15, 10))
ob.grid(column=3, row=int(idx + 1), padx=(15, 10))
name.grid(column=0, row=int(idx + 1))
def getStates(self, *args):
"""Get the input option selection in (idx,YN) format."""
states = []
for idx, bit in enumerate([x.get() for x in self.stringVarList]):
if bit != '-':
states.append((self.options[idx], bit))
return states
def chgEvent(self):
"""Trigger an event in the master frame if a change is made."""
self.master.event_generate('<<RdBtnChg>>')
class RadiobuttonEntry(ttk.Frame):
"""State entry for all DMs, and controls for adding the infeasibles.
Uses a set of RadioButtonSeries elements.
"""
def __init__(self, master, conflict):
"""Initialize the widget."""
ttk.Frame.__init__(self, master)
self.conflict = conflict
self.dmLookup = {dm.name: dm for dm in self.conflict.decisionMakers}
dmNames = tuple(self.dmLookup.keys())
self.activeDMname = StringVar(value=dmNames[0])
self.activeDM = self.dmLookup[dmNames[0]]
dmSelLabel = ttk.Label(self, text="Decision Maker")
dmSelLabel.grid(column=0, row=0)
self.dmSelector = ttk.Combobox(self, textvariable=self.activeDMname,
values=dmNames, state='readonly')
self.dmSelector.grid(column=1, row=0, sticky=NSEW)
self.dmSelector.bind('<<ComboboxSelected>>', self.dmSel)
self.rbeCanvas = Canvas(self)
self.rdBtnFrame = ttk.Frame(self.rbeCanvas)
self.scrollY = ttk.Scrollbar(self, orient=VERTICAL,
command=self.rbeCanvas.yview)
self.rbeCanvas.grid(column=0, row=1, columnspan=2, sticky=NSEW)
self.scrollY.grid(column=2, row=1, sticky=NSEW)
self.rbeCanvas.configure(yscrollcommand=self.scrollY.set)
self.canvWindow = self.rbeCanvas.create_window(
(0, 0), window=self.rdBtnFrame, anchor='nw')
self.rowconfigure(1, weight=1)
self.entryText = StringVar(value='')
vcmd = self.register(self.onValidate)
self.entryBx = ttk.Entry(self, textvariable=self.entryText,
validate="key",
validatecommand=(vcmd, '%S', '%P'))
self.entryBx.grid(column=0, row=2, columnspan=2, sticky=NSEW)
self.entryBx.bind('<Return>', self.generateAdd)
self.warnText = StringVar(value='')
self.addBtn = ttk.Button(self, text='Remove as Misperceived Condition',
command=self.generateAdd)
self.mutExBtn = ttk.Button(self,
text='Perceived as Mutually Exclusive',
command=self.generateMutEx)
self.warnLab = ttk.Label(self, textvariable=self.warnText)
self.warnLab.grid(column=0, row=3, sticky=NSEW)
self.addBtn.grid(column=0, row=4, columnspan=2, sticky=NSEW)
self.mutExBtn.grid(column=0, row=5, columnspan=2, sticky=NSEW)
self.reloadOpts()
def resize(self, event=None):
"""Resize the scroll region of the main canvas element."""
self.rbeCanvas.configure(scrollregion=self.rbeCanvas.bbox("all"))
self.rbeCanvas["width"] = self.rbeCanvas.bbox("all")[2]
def generateAdd(self, *args):
"""Prompt response to addition of an infeasible state."""
self.event_generate('<<addMisperceived>>')
def generateMutEx(self, *args):
"""Prompt response to addition of a mutually exclusive set."""
self.event_generate('<<AddMutEx>>')
def reloadOpts(self):
"""Reload all options for all DMs."""
self.rbeCanvas.delete(self.canvWindow)
self.rdBtnFrame.destroy()
self.rdBtnFrame = ttk.Frame(self.rbeCanvas)
self.canvWindow = self.rbeCanvas.create_window(
(0, 0), window=self.rdBtnFrame, anchor='nw')
self.rdBtnFrame.bind('<<RdBtnChg>>', self.rdBtnChgCmd)
self.rdBtnFrame.bind("<Configure>", self.resize)
self.rdBtnSrs = []
self.stringVarList = []
for x, dm in enumerate(self.conflict.decisionMakers):
a = RadiobuttonSeries(self.rdBtnFrame, dm)
self.rdBtnSrs.append(a)
a.setOpts(dm.options)
a.grid(column=0, row=int(x), sticky=NSEW)
self.stringVarList += a.stringVarList
self.rdBtnChgCmd()
def setStates(self, dashOne):
"""Change the condition selected on the radio buttons."""
if len(dashOne) != len(self.stringVarList):
raise Exception('string length does not match number '
'of options: {}'.format(dashOne))
for x, y in enumerate(dashOne):
self.stringVarList[x].set(y)
self.entryText.set(dashOne)
def getStates(self):
"""Get the condition selected on the radio buttons."""
states = []
for srs in self.rdBtnSrs:
states.extend(srs.getStates())
return states
def onValidate(self, chg, res):
"""Validate manually entered condition characters and length."""
if chg in ['Y', 'N', 'y', 'n', '-']:
if len(res) < len(self.stringVarList):
self.warnText.set('Entry too short')
return True
if len(res) == len(self.stringVarList):
self.setStates(res.upper())
self.warnText.set('')
return True
return False
def rdBtnChgCmd(self, *args):
"""Set the entry box value to match the radiobuttons."""
val = ''.join([x.get() for x in self.stringVarList])
self.entryText.set(val)
def dmSel(self, *args):
"""Prompt response to a different DM being selected."""
dmName = self.activeDMname.get()
self.activeDM = self.dmLookup[dmName]
self.event_generate('<<ChangeDM>>')
# ######################
def main():
"""Run widget in test window."""
root = Tk()
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
g1 = ConflictModel()
g1.load_from_file('Examples/SyriaIraq.gmcr')
radFrame = RadiobuttonEntry(root, g1)
radFrame.grid(column=0, row=0, sticky=(N, W))
root.mainloop()
print(radFrame.getStates())
if __name__ == '__main__':
main()