forked from onp/gmcr-py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwidgets_f04_01_prefRadioButton.py
369 lines (296 loc) · 13.3 KB
/
widgets_f04_01_prefRadioButton.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
# Copyright: (c) Oskar Petersons 2013
"""Widgets for selecting a state using radio buttons for each option.
Loaded by the frame_04_preferencePrioritization module.
Nearly a clone of widgets_f02_01_radioButtonEntry.
"""
from tkinter import Tk, N, S, E, W, VERTICAL, StringVar, Canvas
from tkinter import ttk
from data_01_conflictModel import ConflictModel
import re
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):
"""State entry widget for a single decision maker."""
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):
"""Set the list of options to be displayed in the series."""
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 entered state, 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):
"""Generate event if input is changed."""
self.master.event_generate('<<RdBtnChg>>')
def disable(self):
"""Disable the widget and all children."""
for child in self.winfo_children():
child['state'] = 'disabled'
def enable(self):
"""Enable the widget and all children."""
for child in self.winfo_children():
child['state'] = 'normal'
class RadiobuttonEntry(ttk.Frame):
"""State entry for the entire conflict. A set of RadioButtonSeries."""
def __init__(self, master, conflict):
"""State entry widget for the entire conflict."""
ttk.Frame.__init__(self, master)
self.conflict = conflict
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=0, columnspan=2, sticky=NSEW)
self.scrollY.grid(column=2, row=0, sticky=NSEW)
self.rbeCanvas.configure(yscrollcommand=self.scrollY.set)
self.canvWindow = self.rbeCanvas.create_window((0, 0),
window=self.rdBtnFrame,
anchor='nw')
self.rowconfigure(0, 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=1, sticky=NSEW)
self.entryBx.bind('<Return>', self.generateAdd)
self.warnText = StringVar(value='')
self.warnLab = ttk.Label(self, textvariable=self.warnText, width=18)
self.warnLab.grid(column=1, row=1, sticky=NSEW)
self.codeText = StringVar(value='')
vcmd2 = self.register(self.onValidate2)
self.codeBx = ttk.Entry(self, textvariable=self.codeText,
validate="key",
validatecommand=(vcmd2, '%S', '%P'))
self.codeBx.grid(column=0, row=2, sticky=NSEW)
self.codeBx.bind('<Return>', self.generateAdd)
self.warnText2 = StringVar(value='')
self.warnLab2 = ttk.Label(self, textvariable=self.warnText2)
self.warnLab2.grid(column=1, row=2, sticky=NSEW)
self.addBtn = ttk.Button(self, text='Add as Prefered State',
command=self.generateAdd)
self.stageBtn = ttk.Button(self, text='Add to Staging',
command=self.generateStage)
self.addBtn.grid(column=0, row=4, columnspan=2, sticky=NSEW)
self.stageBtn.grid(column=0, row=5, columnspan=2, sticky=NSEW)
self.isDisabled = False
self.columnconfigure(0, weight=1)
self.reloadOpts()
self.regexValidChars = re.compile(r'^[-\d, fi]*$')
self.regexStatesIf = re.compile(r'^ *(-)?(\d+) *iff? *(-)?(\d+) *$')
self.regexStates = re.compile(r' *(-)?(\d+) *')
self.hasValidIf = False
def resize(self, event=None):
"""Adjust the canvas widget if the window is resized."""
self.rbeCanvas.configure(scrollregion=self.rbeCanvas.bbox("all"))
self.rbeCanvas["width"] = self.rbeCanvas.bbox("all")[2]
def generateAdd(self, event=None):
"""Generate event if a preference is added."""
self.event_generate('<<AddPref>>')
def generateStage(self, event=None):
"""Generate event if a preference is staged."""
self.event_generate('<<StagePref>>')
def reloadOpts(self):
"""Reload options for all decision makers."""
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()
if self.isDisabled:
self.disable()
def disable(self, event=None):
"""Disable the widget and all children."""
self.isDisabled = True
self.entryBx['state'] = 'disabled'
self.codeBx['state'] = 'disabled'
self.addBtn['state'] = 'disabled'
self.stageBtn['state'] = 'disabled'
for srs in self.rdBtnSrs:
srs.disable()
def enable(self, event=None):
"""Enable the widget and all children."""
self.isDisabled = False
self.entryBx['state'] = 'normal'
self.codeBx['state'] = 'normal'
self.addBtn['state'] = 'normal'
self.stageBtn['state'] = 'normal'
for srs in self.rdBtnSrs:
srs.enable()
def setStates(self, dashOne):
"""Set the states shown on the radiobuttons."""
if dashOne == 'clear':
for var in self.stringVarList:
var.set('-')
self.entryText.set('-' * len(self.stringVarList))
return
if len(dashOne) != len(self.stringVarList):
raise Exception("string is wrong length: {}".format(dashOne))
for x, y in enumerate(dashOne):
self.stringVarList[x].set(y)
self.entryText.set(dashOne)
self.hasValidIf = False
def getStates(self):
"""Get the states shown on the radiobuttons in YN- format."""
if self.hasValidIf:
return self.ifCond
states = []
for srs in self.rdBtnSrs:
states.extend(srs.getStates())
return states
def onValidate(self, chg, res):
"""Validation of entrybox state description string."""
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 onValidate2(self, chg, res):
"""Validate condition input string."""
if self.regexValidChars.match(res):
if "if" in res:
m = self.regexStatesIf.match(res)
if m:
self.warnText2.set('')
self.handleIf(res, m.groups())
else:
self.warnText2.set('Invalid')
else:
states = res.split(',')
sts2 = []
for st in states:
m = self.regexStates.match(st)
if m:
sts2.append(m.groups())
else:
self.warnText2.set('Invalid')
return True
self.warnText2.set('')
setTo = '-' * len(self.stringVarList)
for neg, st in sts2:
if int(st) > len(self.stringVarList):
self.warnText2.set(st + ' is too large')
return True
if setTo[int(st) - 1] != "-":
self.warnText2.set("Too many " + st + "s")
return True
if neg:
setTo = setTo[:(int(st) - 1)] + 'N' + setTo[int(st):]
else:
setTo = setTo[:(int(st) - 1)] + 'Y' + setTo[int(st):]
self.setStates(setTo)
return True
self.warnText2.set('Invalid')
return False
def handleIf(self, string, states):
"""Q if P (equivalent to 'If p, then q')."""
if int(states[1]) > len(self.stringVarList):
self.warnText2.set(states[1] + ' is too large')
return True
elif int(states[3]) > len(self.stringVarList):
self.warnText2.set(states[3] + ' is too large')
return True
elif states[1] == states[3]:
self.warnText2.set("duplicate")
return True
q = [self.conflict.options[int(states[1]) - 1],
"N" if states[0] else "Y"]
nq = [self.conflict.options[int(states[1]) - 1],
"Y" if states[0] else "N"] # not q
p = [self.conflict.options[int(states[3]) - 1],
"N" if states[2] else "Y"]
np = [self.conflict.options[int(states[3]) - 1],
"Y" if states[2] else "N"] # not p
newCondition = None
if "iff" in string:
newCondition = self.conflict.newCompoundCondition([[p, q],
[np, nq]])
else:
newCondition = self.conflict.newCompoundCondition([[p, q], [np, q],
[np, nq]])
self.setStates(' ' * len(self.stringVarList))
self.hasValidIf = True
self.ifCond = newCondition
def rdBtnChgCmd(self, *args):
"""Update display on input through radiobuttons."""
val = ''.join([x.get() for x in self.stringVarList])
self.entryText.set(val)
self.warnText.set('')
val = [[i + 1, x.get()] for i, x in enumerate(self.stringVarList)
if (x.get() != "-")]
outVar = []
for i, x in val:
if x == "N":
outVar.append("-" + str(i))
else:
outVar.append(str(i))
self.codeText.set(", ".join(outVar))
self.warnText2.set('')
# #############################################################################
# ############### TESTING ###########
# #############################################################################
# Code in this section is only run when this module is run by itself. It serves
# as a test of module funcitonality.
def main():
"""Run screen in test window."""
root = Tk()
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
g1 = ConflictModel('Prisoners.gmcr')
radFrame = RadiobuttonEntry(root, g1)
radFrame.grid(column=0, row=0, sticky=(N, W))
root.mainloop()
print(radFrame.getStates())
if __name__ == '__main__':
main()