wizard-tk-bridge 1.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- wizard_tk_bridge/__init__.py +15 -0
- wizard_tk_bridge/_no_text_io.py +99 -0
- wizard_tk_bridge/auto_scroll.py +37 -0
- wizard_tk_bridge/close_binding.py +47 -0
- wizard_tk_bridge/gui_style.py +70 -0
- wizard_tk_bridge/py.typed +0 -0
- wizard_tk_bridge/tk_bridge.py +181 -0
- wizard_tk_bridge/wizard_calendar.py +189 -0
- wizard_tk_bridge/wizard_form.py +640 -0
- wizard_tk_bridge/wizard_path.py +113 -0
- wizard_tk_bridge/wizard_pick_row.py +154 -0
- wizard_tk_bridge/wizard_table.py +259 -0
- wizard_tk_bridge/wizard_typed.py +289 -0
- wizard_tk_bridge/wizard_window.py +440 -0
- wizard_tk_bridge-1.3.dist-info/METADATA +212 -0
- wizard_tk_bridge-1.3.dist-info/RECORD +19 -0
- wizard_tk_bridge-1.3.dist-info/WHEEL +5 -0
- wizard_tk_bridge-1.3.dist-info/licenses/LICENSE.txt +21 -0
- wizard_tk_bridge-1.3.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,640 @@
|
|
|
1
|
+
#! /usr/local/bin/python3
|
|
2
|
+
"""A whole wizard form shown on one screen, and its answer parsing.
|
|
3
|
+
|
|
4
|
+
A form question asks several related fields at once. :class:`FormEditor`
|
|
5
|
+
builds a two-column grid, a label on the left and an input widget on the
|
|
6
|
+
right, one row per :class:`AskField`. It reads one :class:`AnswerField`
|
|
7
|
+
per row, runs the optional partial validator after every change to show
|
|
8
|
+
advisory feedback and disable irrelevant rows, and validates every
|
|
9
|
+
enabled field on submit so a submitted form is always complete.
|
|
10
|
+
|
|
11
|
+
Turning the raw text of a field into its typed answer is the same job on
|
|
12
|
+
a form row and in a standalone question, so :func:`int_answer` lives
|
|
13
|
+
here and is shared with the wizard window. Its text counterpart is
|
|
14
|
+
:func:`wizard_ui_bridge.bridge_helpers.text_answer`, which every bridge
|
|
15
|
+
shares, so a graphical answer is accepted or rejected exactly as a
|
|
16
|
+
console one is.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
# Copyright (c) 2026 Tom Björkholm
|
|
20
|
+
# MIT License
|
|
21
|
+
|
|
22
|
+
import tkinter as tk
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from functools import partial
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from tkinter import ttk
|
|
27
|
+
from typing import Callable, NamedTuple, Optional, Sequence
|
|
28
|
+
from wizard_ui_bridge import AskField, AnswerField, PartialFormValidator, \
|
|
29
|
+
PrefillValues, PrefillValueType, AskTextField, AskIntField, AskPathField, \
|
|
30
|
+
AskYesNoField, AskChoiceField, AskMultiChoiceField, AskFloatField, \
|
|
31
|
+
AskDateField, AskTimeField, AskDateTimeField, AskDurationField, \
|
|
32
|
+
AnswerTextField, AnswerIntField, AnswerPathField, AnswerYesNoField, \
|
|
33
|
+
AnswerChoiceField, AnswerMultiChoiceField
|
|
34
|
+
from wizard_ui_bridge.bridge_helpers import INT_ERROR as _INT_ERROR, \
|
|
35
|
+
int_text, multi_count_message, out_of_range, path_answer, range_error, \
|
|
36
|
+
text_answer
|
|
37
|
+
from wizard_ui_bridge.form_helpers import valid_prefills
|
|
38
|
+
from wizard_tk_bridge.auto_scroll import auto_hide
|
|
39
|
+
from wizard_tk_bridge.gui_style import style_input
|
|
40
|
+
from wizard_tk_bridge.wizard_path import PathRow
|
|
41
|
+
from wizard_tk_bridge.wizard_pick_row import HintEntry, PickRow, TypedInput
|
|
42
|
+
from wizard_tk_bridge.wizard_typed import default_text, field_hint, \
|
|
43
|
+
format_value, is_typed, typed_answer, typed_error, typed_value
|
|
44
|
+
|
|
45
|
+
WRAP_LENGTH = 520
|
|
46
|
+
LABEL_WRAP = 220
|
|
47
|
+
MULTI_HEIGHT = 6
|
|
48
|
+
ENTRY_WIDTH = 34
|
|
49
|
+
INT_WIDTH = 14
|
|
50
|
+
CHOICE_WIDTH = 30
|
|
51
|
+
_CHOICE_REQUIRED = 'Please choose a value.'
|
|
52
|
+
TOOLTIP_BG = '#ffffe0'
|
|
53
|
+
TOOLTIP_WRAP = 320
|
|
54
|
+
TOOLTIP_GAP = 2
|
|
55
|
+
_HANDLED = (AskTextField, AskIntField, AskPathField, AskYesNoField,
|
|
56
|
+
AskChoiceField, AskMultiChoiceField, AskFloatField, AskDateField,
|
|
57
|
+
AskTimeField, AskDateTimeField, AskDurationField)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def handles_field(field: AskField) -> bool:
|
|
61
|
+
"""Return whether the Tk form can show the given field type."""
|
|
62
|
+
return isinstance(field, _HANDLED)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# pylint: disable-next=too-many-arguments
|
|
66
|
+
def int_answer(text: str, nullable: bool, min_value: Optional[int],
|
|
67
|
+
max_value: Optional[int], default: Optional[int]
|
|
68
|
+
) -> tuple[bool, Optional[int], Optional[str]]:
|
|
69
|
+
"""Return whether an integer answer is final, its value, and a reason.
|
|
70
|
+
|
|
71
|
+
An empty answer takes the default, is None when nullable, or is
|
|
72
|
+
re-asked otherwise. A non-empty answer must parse as an integer that
|
|
73
|
+
lies within the inclusive bounds.
|
|
74
|
+
"""
|
|
75
|
+
if text == '':
|
|
76
|
+
if default is not None:
|
|
77
|
+
return (True, default, None)
|
|
78
|
+
return (True, None, None) if nullable else (False, None, _INT_ERROR)
|
|
79
|
+
value = int_text(text)
|
|
80
|
+
if value is None:
|
|
81
|
+
return (False, None, _INT_ERROR)
|
|
82
|
+
if out_of_range(value, min_value, max_value):
|
|
83
|
+
return (False, None, range_error(min_value, max_value))
|
|
84
|
+
return (True, value, None)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class _Input(NamedTuple):
|
|
88
|
+
"""A built input: the widget to place, plus type-specific handles."""
|
|
89
|
+
|
|
90
|
+
widget: tk.Widget
|
|
91
|
+
var: Optional[tk.BooleanVar]
|
|
92
|
+
path: Optional[PathRow]
|
|
93
|
+
typed: Optional[TypedInput] = None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _inside(start: int, size: int, limit: int) -> int:
|
|
97
|
+
"""Return the start coordinate that keeps size within limit."""
|
|
98
|
+
return max(0, min(start, limit - size))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class HelpTooltip:
|
|
102
|
+
"""A hover bubble showing a field's help text over its widgets.
|
|
103
|
+
|
|
104
|
+
The bubble is a label placed over the window that holds the bound
|
|
105
|
+
widgets, shown when the pointer enters one of them and destroyed
|
|
106
|
+
when it leaves, so help appears on hover as it does in the textual
|
|
107
|
+
bridge. A window of its own is drawn with the platform's window
|
|
108
|
+
shape, which on macOS rounds the corners of a borderless window so
|
|
109
|
+
much that a one-line bubble loses its first and last characters. A
|
|
110
|
+
placed label is a plain rectangle on every platform, takes neither
|
|
111
|
+
focus nor a grab, and cannot outlive the widgets it belongs to.
|
|
112
|
+
"""
|
|
113
|
+
|
|
114
|
+
def __init__(self, text: str, anchor: tk.Widget,
|
|
115
|
+
widgets: Sequence[tk.Widget]) -> None:
|
|
116
|
+
"""Bind hover show and hide on each widget for the help text."""
|
|
117
|
+
self.text = text
|
|
118
|
+
self._anchor = anchor
|
|
119
|
+
self._tip: Optional[tk.Label] = None
|
|
120
|
+
for widget in widgets:
|
|
121
|
+
widget.bind('<Enter>', lambda _event: self.show(), add='+')
|
|
122
|
+
widget.bind('<Leave>', lambda _event: self.hide(), add='+')
|
|
123
|
+
widget.bind('<Destroy>', lambda _event: self.hide(), add='+')
|
|
124
|
+
|
|
125
|
+
def show(self) -> None:
|
|
126
|
+
"""Show the help bubble just below the anchor widget."""
|
|
127
|
+
if self._tip is not None:
|
|
128
|
+
return
|
|
129
|
+
host = self._anchor.winfo_toplevel()
|
|
130
|
+
tip = tk.Label(host, text=self.text, background=TOOLTIP_BG,
|
|
131
|
+
relief='solid', borderwidth=1, justify='left',
|
|
132
|
+
wraplength=TOOLTIP_WRAP)
|
|
133
|
+
left, top = self._position(host, tip)
|
|
134
|
+
tip.place(x=left, y=top)
|
|
135
|
+
tip.lift()
|
|
136
|
+
self._tip = tip
|
|
137
|
+
|
|
138
|
+
def hide(self) -> None:
|
|
139
|
+
"""Destroy the help bubble when one is shown."""
|
|
140
|
+
if self._tip is not None and self._tip.winfo_exists():
|
|
141
|
+
self._tip.destroy()
|
|
142
|
+
self._tip = None
|
|
143
|
+
|
|
144
|
+
def _position(self, host: tk.Misc, tip: tk.Label) -> tuple[int, int]:
|
|
145
|
+
"""Return where in host to place the bubble under the anchor."""
|
|
146
|
+
left = self._anchor.winfo_rootx() - host.winfo_rootx()
|
|
147
|
+
top = (self._anchor.winfo_rooty() - host.winfo_rooty()
|
|
148
|
+
+ self._anchor.winfo_height() + TOOLTIP_GAP)
|
|
149
|
+
return (_inside(left, tip.winfo_reqwidth(), host.winfo_width()),
|
|
150
|
+
_inside(top, tip.winfo_reqheight(), host.winfo_height()))
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
@dataclass(frozen=True)
|
|
154
|
+
class FormRow:
|
|
155
|
+
"""One built form row: its field, label, input and help tooltip."""
|
|
156
|
+
|
|
157
|
+
field: AskField
|
|
158
|
+
label: tk.Label
|
|
159
|
+
widget: tk.Widget
|
|
160
|
+
var: Optional[tk.BooleanVar]
|
|
161
|
+
path: Optional[PathRow]
|
|
162
|
+
typed: Optional[TypedInput] = None
|
|
163
|
+
tooltip: Optional[HelpTooltip] = None
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _text_input(grid: tk.Misc, field: AskTextField,
|
|
167
|
+
change: Callable[[], None]) -> _Input:
|
|
168
|
+
"""Build a text entry, masked and without a default when sensitive."""
|
|
169
|
+
entry = tk.Entry(grid, width=ENTRY_WIDTH)
|
|
170
|
+
if field.sensitive:
|
|
171
|
+
entry.configure(show='*')
|
|
172
|
+
elif field.default is not None:
|
|
173
|
+
entry.insert(0, field.default)
|
|
174
|
+
style_input(entry)
|
|
175
|
+
entry.bind('<KeyRelease>', lambda _event: change())
|
|
176
|
+
return _Input(entry, None, None)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _int_input(grid: tk.Misc, field: AskIntField,
|
|
180
|
+
change: Callable[[], None]) -> _Input:
|
|
181
|
+
"""Build a numeric text entry pre-filled with its default."""
|
|
182
|
+
entry = tk.Entry(grid, width=INT_WIDTH)
|
|
183
|
+
if field.default is not None:
|
|
184
|
+
entry.insert(0, str(field.default))
|
|
185
|
+
style_input(entry)
|
|
186
|
+
entry.bind('<KeyRelease>', lambda _event: change())
|
|
187
|
+
return _Input(entry, None, None)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _path_input(grid: tk.Misc, field: AskPathField,
|
|
191
|
+
change: Callable[[], None]) -> _Input:
|
|
192
|
+
"""Build a path entry with a Browse button from the path options."""
|
|
193
|
+
default = field.path_options.default
|
|
194
|
+
initial = '' if default is None else str(default)
|
|
195
|
+
row = PathRow(grid, field.path_options, initial, change)
|
|
196
|
+
return _Input(row.frame, None, row)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _yes_no_input(grid: tk.Misc, field: AskYesNoField,
|
|
200
|
+
change: Callable[[], None]) -> _Input:
|
|
201
|
+
"""Build a check box holding the yes/no default."""
|
|
202
|
+
var = tk.BooleanVar(grid, field.default)
|
|
203
|
+
check = tk.Checkbutton(grid, variable=var, command=change)
|
|
204
|
+
return _Input(check, var, None)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _choice_input(grid: tk.Misc, field: AskChoiceField,
|
|
208
|
+
change: Callable[[], None]) -> _Input:
|
|
209
|
+
"""Build a read-only drop-down, preselecting any default choice."""
|
|
210
|
+
box = ttk.Combobox(grid, values=list(field.choices), state='readonly',
|
|
211
|
+
width=CHOICE_WIDTH)
|
|
212
|
+
if field.default is not None:
|
|
213
|
+
box.set(field.default)
|
|
214
|
+
style_input(box)
|
|
215
|
+
box.bind('<<ComboboxSelected>>', lambda _event: change())
|
|
216
|
+
return _Input(box, None, None)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _multi_input(grid: tk.Misc, field: AskMultiChoiceField,
|
|
220
|
+
change: Callable[[], None]) -> _Input:
|
|
221
|
+
"""Build a multi-selection list, preselecting the default values."""
|
|
222
|
+
box = tk.Listbox(grid, selectmode='multiple', exportselection=False,
|
|
223
|
+
height=min(len(field.choices), MULTI_HEIGHT))
|
|
224
|
+
for choice in field.choices:
|
|
225
|
+
box.insert('end', choice)
|
|
226
|
+
_preselect(box, field.choices, field.default)
|
|
227
|
+
style_input(box)
|
|
228
|
+
box.bind('<<ListboxSelect>>', lambda _event: change())
|
|
229
|
+
return _Input(box, None, None)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _preselect(box: tk.Listbox, choices: Sequence[str],
|
|
233
|
+
default: Optional[Sequence[str]]) -> None:
|
|
234
|
+
"""Select the default values in a multi-selection list."""
|
|
235
|
+
if default is None:
|
|
236
|
+
return
|
|
237
|
+
wanted = set(default)
|
|
238
|
+
for index, choice in enumerate(choices):
|
|
239
|
+
if choice in wanted:
|
|
240
|
+
box.selection_set(index)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _hint_input(grid: tk.Misc, field: AskField,
|
|
244
|
+
change: Callable[[], None]) -> _Input:
|
|
245
|
+
"""Build a placeholder entry for a float, time or duration field."""
|
|
246
|
+
entry = HintEntry(grid, field_hint(field), default_text(field), change)
|
|
247
|
+
return _Input(entry.entry, None, None, entry)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _pick_input(grid: tk.Misc, field: AskField,
|
|
251
|
+
change: Callable[[], None]) -> _Input:
|
|
252
|
+
"""Build a date or date-time entry with a calendar Pick button."""
|
|
253
|
+
row = PickRow(grid, field, field_hint(field), default_text(field), change)
|
|
254
|
+
return _Input(row.frame, None, None, row)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _typed_input(grid: tk.Misc, field: AskField,
|
|
258
|
+
change: Callable[[], None]) -> _Input:
|
|
259
|
+
"""Build the input widget for one of the five typed fields."""
|
|
260
|
+
if isinstance(field, (AskFloatField, AskTimeField, AskDurationField)):
|
|
261
|
+
return _hint_input(grid, field, change)
|
|
262
|
+
return _pick_input(grid, field, change)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _basic_input(grid: tk.Misc, field: AskField,
|
|
266
|
+
change: Callable[[], None]) -> _Input:
|
|
267
|
+
"""Build the input widget for one of the original field kinds."""
|
|
268
|
+
if isinstance(field, AskTextField):
|
|
269
|
+
return _text_input(grid, field, change)
|
|
270
|
+
if isinstance(field, AskIntField):
|
|
271
|
+
return _int_input(grid, field, change)
|
|
272
|
+
if isinstance(field, AskPathField):
|
|
273
|
+
return _path_input(grid, field, change)
|
|
274
|
+
if isinstance(field, AskYesNoField):
|
|
275
|
+
return _yes_no_input(grid, field, change)
|
|
276
|
+
if isinstance(field, AskChoiceField):
|
|
277
|
+
return _choice_input(grid, field, change)
|
|
278
|
+
assert isinstance(field, AskMultiChoiceField)
|
|
279
|
+
return _multi_input(grid, field, change)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _make_input(grid: tk.Misc, field: AskField,
|
|
283
|
+
change: Callable[[], None]) -> _Input:
|
|
284
|
+
"""Build the input widget matching the field type."""
|
|
285
|
+
if is_typed(field):
|
|
286
|
+
return _typed_input(grid, field, change)
|
|
287
|
+
return _basic_input(grid, field, change)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _entry_widget(row: FormRow) -> tk.Entry:
|
|
291
|
+
"""Return the text entry of a text or integer row."""
|
|
292
|
+
assert isinstance(row.widget, tk.Entry)
|
|
293
|
+
return row.widget
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _int_value(row: FormRow, field: AskIntField) -> Optional[int]:
|
|
297
|
+
"""Return the integer value of a row, or its default when empty."""
|
|
298
|
+
text = _entry_widget(row).get()
|
|
299
|
+
return field.default if text == '' else int_text(text)
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _path_value(row: FormRow, field: AskPathField) -> Optional[Path]:
|
|
303
|
+
"""Return the accepted path of a row, or None when not accepted."""
|
|
304
|
+
assert row.path is not None
|
|
305
|
+
_, path, _ = path_answer(row.path.get(), field.path_options)
|
|
306
|
+
return path
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _choice_value(row: FormRow) -> Optional[str]:
|
|
310
|
+
"""Return the chosen value of a row, or None when none is chosen."""
|
|
311
|
+
assert isinstance(row.widget, ttk.Combobox)
|
|
312
|
+
value = row.widget.get()
|
|
313
|
+
return value if value != '' else None
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _multi_selected(row: FormRow) -> list[int]:
|
|
317
|
+
"""Return the selected 0-based indexes of a multi-selection row."""
|
|
318
|
+
assert isinstance(row.widget, tk.Listbox)
|
|
319
|
+
picks = row.widget.curselection() # type: ignore[no-untyped-call]
|
|
320
|
+
return [int(index) for index in picks]
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _multi_values(row: FormRow, field: AskMultiChoiceField) -> list[str]:
|
|
324
|
+
"""Return the chosen values of a multi-selection row, in order."""
|
|
325
|
+
return [field.choices[index] for index in _multi_selected(row)]
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _int_error(row: FormRow, field: AskIntField) -> Optional[str]:
|
|
329
|
+
"""Return the integer row's own validation error, or None."""
|
|
330
|
+
text = _entry_widget(row).get()
|
|
331
|
+
done, _, reason = int_answer(text, field.nullable, field.min_value,
|
|
332
|
+
field.max_value, field.default)
|
|
333
|
+
return None if done else reason
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _multi_error(row: FormRow, field: AskMultiChoiceField) -> Optional[str]:
|
|
337
|
+
"""Return the multi-selection row's count error, or None."""
|
|
338
|
+
return multi_count_message(len(_multi_selected(row)), field.min_select,
|
|
339
|
+
field.max_select)
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _set_widget_state(row: FormRow, enabled: bool) -> None:
|
|
343
|
+
"""Enable or disable a row's input widget, keeping combo read-only."""
|
|
344
|
+
if row.typed is not None:
|
|
345
|
+
row.typed.set_enabled(enabled)
|
|
346
|
+
return
|
|
347
|
+
if row.path is not None:
|
|
348
|
+
row.path.set_enabled(enabled)
|
|
349
|
+
return
|
|
350
|
+
active = 'readonly' if isinstance(row.widget, ttk.Combobox) else 'normal'
|
|
351
|
+
row.widget['state'] = active if enabled else 'disabled'
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _enable_row(row: FormRow, enabled: bool) -> None:
|
|
355
|
+
"""Enable or disable one form row, greying its label when disabled."""
|
|
356
|
+
_set_widget_state(row, enabled)
|
|
357
|
+
row.label.configure(fg='black' if enabled else 'grey')
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _hint_note(field: AskField) -> Optional[str]:
|
|
361
|
+
"""Return the format hint sentence for a typed field, or None."""
|
|
362
|
+
return f'Enter {field_hint(field)}.' if is_typed(field) else None
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _tooltip_text(field: AskField) -> Optional[str]:
|
|
366
|
+
"""Return the tooltip text combining help text and format hint."""
|
|
367
|
+
note = _hint_note(field)
|
|
368
|
+
if field.help_text is None:
|
|
369
|
+
return note
|
|
370
|
+
return field.help_text if note is None else f'{field.help_text}\n{note}'
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _row_tooltip(field: AskField, label: tk.Label,
|
|
374
|
+
widget: tk.Widget) -> Optional[HelpTooltip]:
|
|
375
|
+
"""Return a hover tooltip for the field's help and format hint."""
|
|
376
|
+
text = _tooltip_text(field)
|
|
377
|
+
if text is None:
|
|
378
|
+
return None
|
|
379
|
+
return HelpTooltip(text, label, (label, widget))
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _set_entry_text(entry: tk.Entry, text: str) -> None:
|
|
383
|
+
"""Replace a text or integer entry's text, enabling it if disabled."""
|
|
384
|
+
if entry.get() == text:
|
|
385
|
+
return
|
|
386
|
+
state = entry['state']
|
|
387
|
+
entry['state'] = 'normal'
|
|
388
|
+
entry.delete(0, 'end')
|
|
389
|
+
entry.insert(0, text)
|
|
390
|
+
entry['state'] = state
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _set_combo(box: ttk.Combobox, value: str) -> None:
|
|
394
|
+
"""Set a drop-down's value, enabling it briefly if disabled."""
|
|
395
|
+
if box.get() == value:
|
|
396
|
+
return
|
|
397
|
+
state = box['state']
|
|
398
|
+
box['state'] = 'normal'
|
|
399
|
+
box.set(value)
|
|
400
|
+
box['state'] = state
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def _set_multi(box: tk.Listbox, choices: Sequence[str],
|
|
404
|
+
value: PrefillValueType) -> None:
|
|
405
|
+
"""Select the values of a multi-selection list, enabling it briefly."""
|
|
406
|
+
assert isinstance(value, (list, tuple))
|
|
407
|
+
wanted = set(value)
|
|
408
|
+
state = box['state']
|
|
409
|
+
box['state'] = 'normal'
|
|
410
|
+
box.selection_clear(0, 'end')
|
|
411
|
+
for index, choice in enumerate(choices):
|
|
412
|
+
if choice in wanted:
|
|
413
|
+
box.selection_set(index)
|
|
414
|
+
box['state'] = state
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def _basic_answer(row: FormRow) -> AnswerField:
|
|
418
|
+
"""Return the answer of a row of one of the original field kinds."""
|
|
419
|
+
field = row.field
|
|
420
|
+
if isinstance(field, AskTextField):
|
|
421
|
+
text = _entry_widget(row).get()
|
|
422
|
+
return AnswerTextField(field, text_answer(text, field.nullable,
|
|
423
|
+
field.default))
|
|
424
|
+
if isinstance(field, AskIntField):
|
|
425
|
+
return AnswerIntField(field, _int_value(row, field))
|
|
426
|
+
if isinstance(field, AskPathField):
|
|
427
|
+
return AnswerPathField(field, _path_value(row, field))
|
|
428
|
+
if isinstance(field, AskYesNoField):
|
|
429
|
+
assert row.var is not None
|
|
430
|
+
return AnswerYesNoField(field, bool(row.var.get()))
|
|
431
|
+
if isinstance(field, AskChoiceField):
|
|
432
|
+
return AnswerChoiceField(field, _choice_value(row))
|
|
433
|
+
assert isinstance(field, AskMultiChoiceField)
|
|
434
|
+
return AnswerMultiChoiceField(field, _multi_values(row, field))
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def _basic_error(row: FormRow) -> Optional[str]:
|
|
438
|
+
"""Return the own error of a row of an original field kind, or None."""
|
|
439
|
+
field = row.field
|
|
440
|
+
if isinstance(field, AskIntField):
|
|
441
|
+
return _int_error(row, field)
|
|
442
|
+
if isinstance(field, AskPathField):
|
|
443
|
+
assert row.path is not None
|
|
444
|
+
done, _, reason = path_answer(row.path.get(), field.path_options)
|
|
445
|
+
return None if done else reason
|
|
446
|
+
if isinstance(field, AskChoiceField):
|
|
447
|
+
return None if _choice_value(row) is not None else _CHOICE_REQUIRED
|
|
448
|
+
if isinstance(field, AskMultiChoiceField):
|
|
449
|
+
return _multi_error(row, field)
|
|
450
|
+
return None
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def _row_error(row: FormRow) -> Optional[str]:
|
|
454
|
+
"""Return one row's own validation error, without its field label."""
|
|
455
|
+
if is_typed(row.field):
|
|
456
|
+
assert row.typed is not None
|
|
457
|
+
return typed_error(row.field, row.typed.text())
|
|
458
|
+
return _basic_error(row)
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def _with_label(field: AskField, error: Optional[str]) -> Optional[str]:
|
|
462
|
+
"""Prefix a field's own error with its label, keeping None as None.
|
|
463
|
+
|
|
464
|
+
The whole form shares one status line, so naming the field makes clear
|
|
465
|
+
which row a message such as 'Please enter an integer.' refers to.
|
|
466
|
+
"""
|
|
467
|
+
if error is None:
|
|
468
|
+
return None
|
|
469
|
+
return f'{field.short_question}: {error}'
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
class FormEditor:
|
|
473
|
+
"""A two-column grid that asks a whole wizard form on one screen."""
|
|
474
|
+
|
|
475
|
+
def __init__(self, parent: tk.Misc, fields: Sequence[AskField],
|
|
476
|
+
validator: Optional[PartialFormValidator],
|
|
477
|
+
on_submit: Callable[[list[AnswerField]], None]) -> None:
|
|
478
|
+
"""Build one labelled input row per field, plus a status line."""
|
|
479
|
+
self._validator = validator
|
|
480
|
+
self._on_submit = on_submit
|
|
481
|
+
self._disabled: set[int] = set()
|
|
482
|
+
self._last_changed = 0
|
|
483
|
+
grid = self._scroll_area(parent)
|
|
484
|
+
self._rows = [self._build_row(grid, index, field)
|
|
485
|
+
for index, field in enumerate(fields)]
|
|
486
|
+
self._apply_initial()
|
|
487
|
+
|
|
488
|
+
def _scroll_area(self, parent: tk.Misc) -> tk.Frame:
|
|
489
|
+
"""Build the scrolling field area, returning the frame for the rows.
|
|
490
|
+
|
|
491
|
+
A tall form (many rows) would overflow the fixed-size wizard
|
|
492
|
+
window, so the labelled rows sit in a frame inside a vertically
|
|
493
|
+
scrolling canvas whose scrollbar appears only when it is needed.
|
|
494
|
+
The status line stays below the scroll area so it is always shown.
|
|
495
|
+
"""
|
|
496
|
+
outer = tk.Frame(parent)
|
|
497
|
+
outer.pack(fill='both', expand=True, pady=6)
|
|
498
|
+
outer.rowconfigure(0, weight=1)
|
|
499
|
+
outer.columnconfigure(0, weight=1)
|
|
500
|
+
canvas = tk.Canvas(outer, highlightthickness=0)
|
|
501
|
+
vbar = ttk.Scrollbar(outer, orient='vertical', command=canvas.yview)
|
|
502
|
+
canvas.configure(yscrollcommand=auto_hide(vbar))
|
|
503
|
+
canvas.grid(row=0, column=0, sticky='nsew')
|
|
504
|
+
vbar.grid(row=0, column=1, sticky='ns')
|
|
505
|
+
grid = tk.Frame(canvas)
|
|
506
|
+
canvas.create_window((0, 0), window=grid, anchor='nw')
|
|
507
|
+
grid.bind('<Configure>', lambda _event: canvas.configure(
|
|
508
|
+
scrollregion=canvas.bbox('all')))
|
|
509
|
+
self._status = tk.Label(outer, fg='red', wraplength=WRAP_LENGTH,
|
|
510
|
+
justify='left')
|
|
511
|
+
self._status.grid(row=1, column=0, columnspan=2, sticky='w',
|
|
512
|
+
pady=(6, 0))
|
|
513
|
+
return grid
|
|
514
|
+
|
|
515
|
+
def _apply_initial(self) -> None:
|
|
516
|
+
"""Disable the initially irrelevant rows, showing no message yet."""
|
|
517
|
+
if self._validator is not None:
|
|
518
|
+
result = self._validator(self.answers(), 0)
|
|
519
|
+
self._apply_disabled(result.disable_row_idxs)
|
|
520
|
+
self._apply_prefills(result.prefill_values, 0)
|
|
521
|
+
|
|
522
|
+
def _apply_prefills(self, prefills: PrefillValues, changed: int) -> None:
|
|
523
|
+
"""Write the validator's valid prefills into their row inputs."""
|
|
524
|
+
fields = [row.field for row in self._rows]
|
|
525
|
+
for index, value in valid_prefills(fields, changed, prefills):
|
|
526
|
+
self._write_value(self._rows[index], value)
|
|
527
|
+
|
|
528
|
+
def _write_value(self, row: FormRow, value: PrefillValueType) -> None:
|
|
529
|
+
"""Write one prefill value into a row's input by field type."""
|
|
530
|
+
field = row.field
|
|
531
|
+
if row.typed is not None:
|
|
532
|
+
row.typed.set_text(format_value(value))
|
|
533
|
+
elif isinstance(field, (AskTextField, AskIntField)):
|
|
534
|
+
_set_entry_text(_entry_widget(row), str(value))
|
|
535
|
+
elif isinstance(field, AskPathField):
|
|
536
|
+
assert row.path is not None
|
|
537
|
+
row.path.set_text(str(value))
|
|
538
|
+
elif isinstance(field, AskYesNoField):
|
|
539
|
+
assert row.var is not None
|
|
540
|
+
row.var.set(bool(value))
|
|
541
|
+
elif isinstance(field, AskChoiceField):
|
|
542
|
+
assert isinstance(row.widget, ttk.Combobox)
|
|
543
|
+
_set_combo(row.widget, str(value))
|
|
544
|
+
else:
|
|
545
|
+
assert isinstance(field, AskMultiChoiceField)
|
|
546
|
+
assert isinstance(row.widget, tk.Listbox)
|
|
547
|
+
_set_multi(row.widget, field.choices, value)
|
|
548
|
+
|
|
549
|
+
def _build_row(self, grid: tk.Misc, index: int,
|
|
550
|
+
field: AskField) -> FormRow:
|
|
551
|
+
"""Build and place one labelled input row of the grid."""
|
|
552
|
+
label = tk.Label(grid, text=field.short_question, justify='left',
|
|
553
|
+
wraplength=LABEL_WRAP, anchor='w')
|
|
554
|
+
label.grid(row=index, column=0, sticky='nw', padx=4, pady=3)
|
|
555
|
+
built = _make_input(grid, field, partial(self._changed, index))
|
|
556
|
+
built.widget.grid(row=index, column=1, sticky='w', padx=4, pady=3)
|
|
557
|
+
tooltip = _row_tooltip(field, label, built.widget)
|
|
558
|
+
return FormRow(field, label, built.widget, built.var, built.path,
|
|
559
|
+
built.typed, tooltip)
|
|
560
|
+
|
|
561
|
+
def answers(self) -> list[AnswerField]:
|
|
562
|
+
"""Return the current answer of every row, in field order."""
|
|
563
|
+
return [self._read(index) for index in range(len(self._rows))]
|
|
564
|
+
|
|
565
|
+
def submit(self) -> None:
|
|
566
|
+
"""Validate every enabled field and submit when all pass."""
|
|
567
|
+
answers = self.answers()
|
|
568
|
+
error = self._first_error()
|
|
569
|
+
if error is not None:
|
|
570
|
+
self._show(error)
|
|
571
|
+
return
|
|
572
|
+
if self._validator_blocks(answers):
|
|
573
|
+
return
|
|
574
|
+
self._on_submit(answers)
|
|
575
|
+
|
|
576
|
+
def _validator_blocks(self, answers: list[AnswerField]) -> bool:
|
|
577
|
+
"""Run the whole-form validator and return whether it blocks."""
|
|
578
|
+
if self._validator is None:
|
|
579
|
+
return False
|
|
580
|
+
result = self._validator(answers, self._last_changed)
|
|
581
|
+
self._apply_disabled(result.disable_row_idxs)
|
|
582
|
+
if not result.is_valid:
|
|
583
|
+
self._show(result.message)
|
|
584
|
+
return not result.is_valid
|
|
585
|
+
|
|
586
|
+
def _changed(self, index: int) -> None:
|
|
587
|
+
"""React to a field change with live feedback and row enabling."""
|
|
588
|
+
self._last_changed = index
|
|
589
|
+
self._show(self._feedback(self.answers(), index))
|
|
590
|
+
|
|
591
|
+
def _feedback(self, answers: list[AnswerField], index: int) -> str:
|
|
592
|
+
"""Return the live message for the field that just changed."""
|
|
593
|
+
validator_msg = self._run_validator(answers, index)
|
|
594
|
+
if index in self._disabled:
|
|
595
|
+
return validator_msg
|
|
596
|
+
own = self._field_error(index)
|
|
597
|
+
return validator_msg if own is None else own
|
|
598
|
+
|
|
599
|
+
def _run_validator(self, answers: list[AnswerField], index: int) -> str:
|
|
600
|
+
"""Apply the validator's disabled rows and return its message."""
|
|
601
|
+
if self._validator is None:
|
|
602
|
+
return ''
|
|
603
|
+
result = self._validator(answers, index)
|
|
604
|
+
self._apply_disabled(result.disable_row_idxs)
|
|
605
|
+
self._apply_prefills(result.prefill_values, index)
|
|
606
|
+
return '' if result.is_valid else result.message
|
|
607
|
+
|
|
608
|
+
def _first_error(self) -> Optional[str]:
|
|
609
|
+
"""Return the first enabled field's own error, or None."""
|
|
610
|
+
for index in range(len(self._rows)):
|
|
611
|
+
if index in self._disabled:
|
|
612
|
+
continue
|
|
613
|
+
error = self._field_error(index)
|
|
614
|
+
if error is not None:
|
|
615
|
+
return error
|
|
616
|
+
return None
|
|
617
|
+
|
|
618
|
+
def _apply_disabled(self, disable_row_idxs: tuple[int, ...]) -> None:
|
|
619
|
+
"""Enable or disable each row to match the validator result."""
|
|
620
|
+
self._disabled = set(disable_row_idxs)
|
|
621
|
+
for index, row in enumerate(self._rows):
|
|
622
|
+
_enable_row(row, index not in self._disabled)
|
|
623
|
+
|
|
624
|
+
def _show(self, message: str) -> None:
|
|
625
|
+
"""Show a status message below the form."""
|
|
626
|
+
self._status.config(text=message)
|
|
627
|
+
|
|
628
|
+
def _read(self, index: int) -> AnswerField:
|
|
629
|
+
"""Return the current answer of one row read from its widget."""
|
|
630
|
+
row = self._rows[index]
|
|
631
|
+
if is_typed(row.field):
|
|
632
|
+
assert row.typed is not None
|
|
633
|
+
value = typed_value(row.field, row.typed.text())
|
|
634
|
+
return typed_answer(row.field, value)
|
|
635
|
+
return _basic_answer(row)
|
|
636
|
+
|
|
637
|
+
def _field_error(self, index: int) -> Optional[str]:
|
|
638
|
+
"""Return one field's own error, prefixed with its label."""
|
|
639
|
+
row = self._rows[index]
|
|
640
|
+
return _with_label(row.field, _row_error(row))
|