Using Checkboxes to return a list
Here is a solution that updates the list as soon as you check a box.
(* myCheckbox add or remove "elt" to/from the list "choice" *)
SetAttributes[myCheckbox, HoldFirst];
myCheckbox[choice_, elt_] :=
Checkbox[Dynamic[MemberQ[choice, elt],
If[#, AppendTo[choice, elt], choice = DeleteCases[choice, elt]] &]]
choice = {};
Dynamic[choice]
Column[Table[
Row[Row [{myCheckbox[choice, {alfa, #}], #}, " ",
Alignment -> Left] & /@ Range[-alfa, 3], " "], {alfa, 5,
0, -1}], Alignment -> Right]
choice
{{4, -4}, {4, -2}, {2, -2}, {0, 0}, {0, 1}}
Your approach with Column[Table[CheckboxBar ...]]
has the drawback that if your checkbox labels have not the same size (vertically), your columns will be missaligned. This problem is solved if you use instead a Grid[]
of the myCheckbox[]
above. Example :
choice2 = {};
Dynamic[choice2]
Grid[{{Row[{myCheckbox[choice2, "A"], "A"}],
Row[{myCheckbox[choice2, "B"], "B"}]}, {,
Row[{myCheckbox[choice2, "C"], "CCCCC"}]}}, Alignment -> Left]
checkboxToList[rows_] := DynamicModule[{cbb},
cbb = ConstantArray[{0}, rows];
Panel@Column[{
Column[
Table[
With[{pos = alfa + 1},
CheckboxBar[Dynamic[cbb[[pos]]], Range[-alfa, 3]]], {alfa, rows - 1,
0, -1}]
, Alignment -> Right]
,
Button["Checkboxes to List",
CellPrint@ExpressionCell@Flatten[
Transpose[{Range[0, Length@cbb - 1],
cbb}] /. {{a_, {b__}} :> ({a, #} & /@ {b}), {a_, {}} -> Nothing},
1]]
}]
]
checkboxToList[6]
Edit 1:
SetAttributes[checkboxToList, HoldAll]
checkboxToList[rows_, out_] :=
DynamicModule[{cbb}, cbb = ConstantArray[{0}, rows];
Panel@Column[{Column[
Table[With[{pos = alfa + 1},
CheckboxBar[Dynamic[cbb[[pos]]], Range[-alfa, 3]]], {alfa, rows - 1,
0, -1}], Alignment -> Right],
Button["Checkboxes to List",
out = Flatten[
Transpose[{Range[0, Length@cbb - 1],
cbb}] /. {{a_, {b__}} :> ({a, #} & /@ {b}), {a_, {}} -> Nothing},
1]]}]]
checkboxToList[6, ans]
Edit 2:
checkboxToList[rows_] := DynamicModule[{cbb}, cbb = ConstantArray[{0}, rows];
Panel@Column[{Column[
Table[With[{pos = alfa + 1},
CheckboxBar[Dynamic[cbb[[pos]]], Range[-alfa, 3]]], {alfa, rows - 1,
0, -1}], Alignment -> Right], Button["Checkboxes to List",
MakeExpression[NotebookRead[PreviousCell[]], StandardForm] /.
HoldPattern[{__, out_ = checkboxToList[_]}] :> (out =
Flatten[Transpose[{Range[0, Length@cbb - 1],
cbb}] /. {{a_, {b__}} :> ({a, #} & /@ {b}), {a_, {}} ->
Nothing}, 1]) // ReleaseHold]}]]
ans = checkboxToList[6]