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,15 @@
|
|
|
1
|
+
#! /usr/bin/env python3
|
|
2
|
+
"""Public API for the wizard user interface Tk bridge.
|
|
3
|
+
|
|
4
|
+
WizardUiBridgeTk is a WizardUiBridge that asks every question through
|
|
5
|
+
real Tkinter widgets, in a window of its own or embedded in an area an
|
|
6
|
+
application already built. See wizard_tk_bridge.tk_bridge for the three
|
|
7
|
+
ways an application can show the wizard.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
# Copyright (c) 2026 Tom Björkholm
|
|
11
|
+
# MIT License
|
|
12
|
+
|
|
13
|
+
from wizard_tk_bridge.tk_bridge import WizardUiBridgeTk
|
|
14
|
+
|
|
15
|
+
__all__ = ['WizardUiBridgeTk']
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
#! /usr/local/bin/python3
|
|
2
|
+
"""NoTextIO can be used as a TextIO object that does nothing."""
|
|
3
|
+
|
|
4
|
+
# Copyright (c) 2026 Tom Björkholm
|
|
5
|
+
# MIT License
|
|
6
|
+
|
|
7
|
+
from typing import Optional, override
|
|
8
|
+
from collections.abc import Iterable
|
|
9
|
+
from types import TracebackType
|
|
10
|
+
import io
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class NoTextIO(io.StringIO):
|
|
14
|
+
"""NoTextIO can be used as a TextIO object that does nothing.
|
|
15
|
+
|
|
16
|
+
When a function expects a TextIO object for output, you can pass in
|
|
17
|
+
a NoTextIO object and no output will be produced.
|
|
18
|
+
The difference compared to using StringIO to suppress output is that
|
|
19
|
+
the NoTextIO does not store any data, so no matter how much is
|
|
20
|
+
written to it, you do not risk running out of memory.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
@override
|
|
24
|
+
def write(self, s: str) -> int:
|
|
25
|
+
"""Write a string to the NoTextIO object.
|
|
26
|
+
|
|
27
|
+
This method does nothing and returns length of the string.
|
|
28
|
+
"""
|
|
29
|
+
return len(s)
|
|
30
|
+
|
|
31
|
+
@override
|
|
32
|
+
def writelines(self, # type: ignore[override]
|
|
33
|
+
lines: Iterable[str]) -> None:
|
|
34
|
+
"""Write a list of strings to the NoTextIO object.
|
|
35
|
+
|
|
36
|
+
This method does nothing and returns None.
|
|
37
|
+
"""
|
|
38
|
+
_ = lines
|
|
39
|
+
|
|
40
|
+
@override
|
|
41
|
+
def flush(self) -> None:
|
|
42
|
+
"""Flush the NoTextIO object.
|
|
43
|
+
|
|
44
|
+
This method does nothing and returns None.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
@override
|
|
48
|
+
def close(self) -> None:
|
|
49
|
+
"""Close the NoTextIO object.
|
|
50
|
+
|
|
51
|
+
This method does nothing and returns None.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
@override
|
|
55
|
+
def seek(self, offset: int, whence: int = io.SEEK_SET, /) -> int:
|
|
56
|
+
"""Seek to a position in the NoTextIO object.
|
|
57
|
+
|
|
58
|
+
This method does nothing and returns 0.
|
|
59
|
+
"""
|
|
60
|
+
_ = offset
|
|
61
|
+
_ = whence
|
|
62
|
+
return 0
|
|
63
|
+
|
|
64
|
+
@override
|
|
65
|
+
def tell(self) -> int:
|
|
66
|
+
"""Get the current position in the NoTextIO object.
|
|
67
|
+
|
|
68
|
+
This method does nothing and returns 0.
|
|
69
|
+
"""
|
|
70
|
+
return 0
|
|
71
|
+
|
|
72
|
+
@override
|
|
73
|
+
def truncate(self, size: Optional[int] = None, /) -> int:
|
|
74
|
+
"""Truncate the NoTextIO object.
|
|
75
|
+
|
|
76
|
+
This method does nothing and returns 0.
|
|
77
|
+
"""
|
|
78
|
+
_ = size
|
|
79
|
+
return 0
|
|
80
|
+
|
|
81
|
+
@override
|
|
82
|
+
def __enter__(self) -> 'NoTextIO':
|
|
83
|
+
"""Enter the NoTextIO object.
|
|
84
|
+
|
|
85
|
+
This method does nothing and returns the NoTextIO object.
|
|
86
|
+
"""
|
|
87
|
+
return self
|
|
88
|
+
|
|
89
|
+
@override
|
|
90
|
+
def __exit__(self, exc_type: Optional[type[BaseException]],
|
|
91
|
+
exc_value: Optional[BaseException],
|
|
92
|
+
traceback: Optional[TracebackType]) -> None:
|
|
93
|
+
"""Exit the NoTextIO object.
|
|
94
|
+
|
|
95
|
+
This method does nothing.
|
|
96
|
+
"""
|
|
97
|
+
_ = exc_type
|
|
98
|
+
_ = exc_value
|
|
99
|
+
_ = traceback
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
#! /usr/local/bin/python3
|
|
2
|
+
"""A scroll command that shows a scrollbar only while it can scroll.
|
|
3
|
+
|
|
4
|
+
A table that fits its area needs no scrollbar, and a scrollbar that is
|
|
5
|
+
always shown wastes space and hints at hidden content that is not there.
|
|
6
|
+
:func:`auto_hide` returns the scroll command for a scrolling widget: the
|
|
7
|
+
command hides the scrollbar while the whole range is visible and shows it
|
|
8
|
+
again once the widget grows past its area. It works for any widget that
|
|
9
|
+
reports its position through an ``xscrollcommand`` or ``yscrollcommand``,
|
|
10
|
+
so a wizard table's canvas and any other scrolling widget can share it.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
# Copyright (c) 2026 Tom Björkholm
|
|
14
|
+
# MIT License
|
|
15
|
+
|
|
16
|
+
from tkinter import ttk
|
|
17
|
+
from typing import Callable
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def auto_hide(scrollbar: ttk.Scrollbar
|
|
21
|
+
) -> Callable[[float | str, float | str], None]:
|
|
22
|
+
"""Return a scroll command that hides the scrollbar when it is full.
|
|
23
|
+
|
|
24
|
+
The result is used as a widget's ``xscrollcommand`` or
|
|
25
|
+
``yscrollcommand``. Tk reports the position as two fractions, which it
|
|
26
|
+
passes as strings, so the command accepts either a number or its
|
|
27
|
+
string form. The scrollbar must be laid out with the grid manager,
|
|
28
|
+
whose ``grid_remove`` remembers its cell across the hide.
|
|
29
|
+
"""
|
|
30
|
+
def command(first: float | str, last: float | str) -> None:
|
|
31
|
+
"""Hide or show the scrollbar, then move its thumb to the view."""
|
|
32
|
+
if float(first) <= 0.0 and float(last) >= 1.0:
|
|
33
|
+
scrollbar.grid_remove()
|
|
34
|
+
else:
|
|
35
|
+
scrollbar.grid()
|
|
36
|
+
scrollbar.set(first, last)
|
|
37
|
+
return command
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
#! /usr/local/bin/python3
|
|
2
|
+
"""Bind the close-window key to a secondary window's close action.
|
|
3
|
+
|
|
4
|
+
On macOS the Tk toolkit does not close a window when the user presses
|
|
5
|
+
Cmd-W, so every secondary window binds that key here. Cmd-W is bound on
|
|
6
|
+
every platform, where it is harmless without a Command key, and Ctrl-W is
|
|
7
|
+
added on Windows, its customary close-window shortcut. The bound action
|
|
8
|
+
defaults to destroying the window but may be the window's own cancel or
|
|
9
|
+
abort handler, so the key behaves exactly like the window close button.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
# Copyright (c) 2026 Tom Björkholm
|
|
13
|
+
# MIT License
|
|
14
|
+
|
|
15
|
+
import sys
|
|
16
|
+
import tkinter as tk
|
|
17
|
+
from typing import Callable, Optional
|
|
18
|
+
|
|
19
|
+
CLOSE_ACCELERATOR = 'Command-W'
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _close_events() -> list[str]:
|
|
23
|
+
"""Return the key patterns that close a window on this platform."""
|
|
24
|
+
if sys.platform.startswith('win'):
|
|
25
|
+
return ['<Command-w>', '<Control-w>']
|
|
26
|
+
return ['<Command-w>']
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _perform_close(win: tk.Toplevel,
|
|
30
|
+
on_close: Optional[Callable[[], None]]) -> str:
|
|
31
|
+
"""Run the window's close action and stop further event handling."""
|
|
32
|
+
(win.destroy if on_close is None else on_close)()
|
|
33
|
+
return 'break'
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def bind_close(win: tk.Toplevel,
|
|
37
|
+
on_close: Optional[Callable[[], None]] = None) -> None:
|
|
38
|
+
"""Bind the close-window key to run the window's close action.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
win: The secondary window to close on the key press.
|
|
42
|
+
on_close: The close action, defaulting to destroying the window.
|
|
43
|
+
A window that cancels or aborts on close passes its own
|
|
44
|
+
handler, so the key matches its window close button.
|
|
45
|
+
"""
|
|
46
|
+
for event in _close_events():
|
|
47
|
+
win.bind(event, lambda _event: _perform_close(win, on_close))
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
#! /usr/local/bin/python3
|
|
2
|
+
"""Shared look and focus helpers for the Tkinter input windows.
|
|
3
|
+
|
|
4
|
+
Editable input widgets blend into the window background on some
|
|
5
|
+
platforms, so the user cannot tell an entry, drop-down or list from the
|
|
6
|
+
surrounding window. :func:`style_input` gives such a widget a white
|
|
7
|
+
field and a thin border so it stands out. :func:`focus_first_input`
|
|
8
|
+
puts the keyboard focus on the first editable widget of a window, so the
|
|
9
|
+
user can start typing as soon as the window opens.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
# Copyright (c) 2026 Tom Björkholm
|
|
13
|
+
# MIT License
|
|
14
|
+
|
|
15
|
+
import tkinter as tk
|
|
16
|
+
from tkinter import ttk
|
|
17
|
+
from typing import Optional
|
|
18
|
+
|
|
19
|
+
INPUT_BG = 'white'
|
|
20
|
+
INPUT_STYLE = 'Input.TCombobox'
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def style_input(widget: tk.Widget) -> None:
|
|
24
|
+
"""Make one editable input widget stand out from the background.
|
|
25
|
+
|
|
26
|
+
A classic entry, text box or list gets a white field and a thin
|
|
27
|
+
solid border. A drop-down keeps its arrow but gets a white field
|
|
28
|
+
through a shared ttk style. Any other widget is left unchanged. The
|
|
29
|
+
ttk styling is best-effort: a native theme that ignores field colors
|
|
30
|
+
leaves the drop-down as it is.
|
|
31
|
+
"""
|
|
32
|
+
if isinstance(widget, ttk.Widget):
|
|
33
|
+
if isinstance(widget, ttk.Combobox):
|
|
34
|
+
_style_combobox(widget)
|
|
35
|
+
return
|
|
36
|
+
if isinstance(widget, (tk.Entry, tk.Text, tk.Listbox)):
|
|
37
|
+
widget.configure(background=INPUT_BG, relief='solid', borderwidth=1)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _style_combobox(widget: ttk.Combobox) -> None:
|
|
41
|
+
"""Give a drop-down a white field through a shared ttk style."""
|
|
42
|
+
style = ttk.Style(widget)
|
|
43
|
+
style.configure(INPUT_STYLE, fieldbackground=INPUT_BG)
|
|
44
|
+
style.map(INPUT_STYLE, fieldbackground=[('readonly', INPUT_BG)])
|
|
45
|
+
widget.configure(style=INPUT_STYLE)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def focus_first_input(window: tk.Misc) -> None:
|
|
49
|
+
"""Give the keyboard focus to the first editable input, if any."""
|
|
50
|
+
target = _first_input(window)
|
|
51
|
+
if target is not None:
|
|
52
|
+
target.focus_set()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _first_input(parent: tk.Misc) -> Optional[tk.Misc]:
|
|
56
|
+
"""Return the first editable input under parent, in child order."""
|
|
57
|
+
for child in parent.winfo_children():
|
|
58
|
+
if _is_input(child):
|
|
59
|
+
return child
|
|
60
|
+
found = _first_input(child)
|
|
61
|
+
if found is not None:
|
|
62
|
+
return found
|
|
63
|
+
return None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _is_input(widget: tk.Misc) -> bool:
|
|
67
|
+
"""Return whether the widget is an editable input to fill in."""
|
|
68
|
+
if not isinstance(widget, (tk.Entry, tk.Listbox, tk.Text)):
|
|
69
|
+
return False
|
|
70
|
+
return str(widget.cget('state')) != 'disabled'
|
|
File without changes
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
#! /usr/local/bin/python3
|
|
2
|
+
"""Graphical Tkinter bridge that drives a synchronous wizard.
|
|
3
|
+
|
|
4
|
+
:class:`WizardUiBridgeTk` is a concrete :class:`WizardUiBridge` that
|
|
5
|
+
overrides every typed ask method with a real Tkinter control, including
|
|
6
|
+
the GUI-recommended ones: ask_path() opens a native file or directory
|
|
7
|
+
picker, and ask_form() shows a whole form on one screen so the user
|
|
8
|
+
answers related fields together in any order. All questions of one
|
|
9
|
+
wizard session are answered in a single reused
|
|
10
|
+
:class:`~wizard_tk_bridge.wizard_window.WizardWindow`, so the session
|
|
11
|
+
does not jump around the display.
|
|
12
|
+
|
|
13
|
+
The bridge supports three ways an application can show the wizard:
|
|
14
|
+
|
|
15
|
+
- In a new window of its own: give ``parent``, the Tk widget the new
|
|
16
|
+
window is shown over. This suits an application with other windows.
|
|
17
|
+
- Embedded in an area the application already built: give ``area``, the
|
|
18
|
+
frame or other container the wizard should fill instead of a window of
|
|
19
|
+
its own.
|
|
20
|
+
- In a window of its own over a hidden root the bridge itself owns: give
|
|
21
|
+
neither ``parent`` nor ``area``. This suits a standalone CLI program
|
|
22
|
+
that has no other Tkinter code.
|
|
23
|
+
|
|
24
|
+
At most one of ``parent`` and ``area`` may be given.
|
|
25
|
+
|
|
26
|
+
Whichever of the three is used, ``modal`` decides whether the wizard
|
|
27
|
+
grabs its window (or the window containing ``area``) for the duration of
|
|
28
|
+
the session, so the rest of that window is unusable meanwhile. The
|
|
29
|
+
application is best placed to decide this, since only it knows whether
|
|
30
|
+
its other content should stay usable while the wizard runs.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
# Copyright (c) 2026 Tom Björkholm
|
|
34
|
+
# MIT License
|
|
35
|
+
|
|
36
|
+
from typing import Optional, Sequence, TextIO
|
|
37
|
+
from pathlib import Path
|
|
38
|
+
import tkinter as tk
|
|
39
|
+
from wizard_ui_bridge import AnswerFields, AskField, AskFields, PartialCheck, \
|
|
40
|
+
PartialFormValidator, PathAskOptions, TableCell, TableColumn, \
|
|
41
|
+
WizardUiBridge
|
|
42
|
+
from wizard_tk_bridge._no_text_io import NoTextIO
|
|
43
|
+
from wizard_tk_bridge.wizard_form import handles_field
|
|
44
|
+
from wizard_tk_bridge.wizard_window import WizardWindow
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class WizardUiBridgeTk(WizardUiBridge):
|
|
48
|
+
"""Bridge that answers wizard prompts through Tkinter widgets."""
|
|
49
|
+
|
|
50
|
+
def __init__(self, parent: Optional[tk.Misc] = None,
|
|
51
|
+
area: Optional[tk.Misc] = None, modal: bool = True,
|
|
52
|
+
log: Optional[TextIO] = None) -> None:
|
|
53
|
+
"""Store where and how to show the wizard, and the optional log.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
parent: The widget the wizard's own new window is shown over.
|
|
57
|
+
Leave both parent and area as None for a standalone
|
|
58
|
+
bridge that owns its hidden root.
|
|
59
|
+
area: The existing container the wizard fills instead of a
|
|
60
|
+
window of its own. It cannot be given together with
|
|
61
|
+
parent.
|
|
62
|
+
modal: Whether the wizard grabs its window (or area's window)
|
|
63
|
+
for the session; see the module docstring.
|
|
64
|
+
log: Stream that receives low-level wizard diagnostics.
|
|
65
|
+
Raises:
|
|
66
|
+
ValueError: Both parent and area were given.
|
|
67
|
+
"""
|
|
68
|
+
if parent is not None and area is not None:
|
|
69
|
+
raise ValueError('Give at most one of parent and area.')
|
|
70
|
+
self._root: Optional[tk.Tk] = None
|
|
71
|
+
if parent is None and area is None:
|
|
72
|
+
self._root = tk.Tk()
|
|
73
|
+
self._root.withdraw()
|
|
74
|
+
parent = self._root
|
|
75
|
+
self._parent = parent
|
|
76
|
+
self._area = area
|
|
77
|
+
self._modal = modal
|
|
78
|
+
self._log = log
|
|
79
|
+
self._window: Optional[WizardWindow] = None
|
|
80
|
+
|
|
81
|
+
def ask_text(self, question: str, re_ask_reason: Optional[str] = None,
|
|
82
|
+
nullable: bool = False, *, default: Optional[str] = None,
|
|
83
|
+
sensitive: bool = False) -> Optional[str]:
|
|
84
|
+
"""Ask for free text; see WizardUiBridge.ask_text."""
|
|
85
|
+
if sensitive and default is not None:
|
|
86
|
+
raise ValueError('default is not allowed for sensitive input')
|
|
87
|
+
return self._window_obj().ask_text(question, re_ask_reason, nullable,
|
|
88
|
+
default, sensitive)
|
|
89
|
+
|
|
90
|
+
# pylint: disable-next=too-many-arguments
|
|
91
|
+
def ask_int(self, question: str, re_ask_reason: Optional[str] = None, *,
|
|
92
|
+
nullable: bool = False, min_value: Optional[int] = None,
|
|
93
|
+
max_value: Optional[int] = None,
|
|
94
|
+
default: Optional[int] = None) -> Optional[int]:
|
|
95
|
+
"""Ask for an integer within optional bounds; see ask_int."""
|
|
96
|
+
return self._window_obj().ask_int(question, re_ask_reason, nullable,
|
|
97
|
+
min_value, max_value, default)
|
|
98
|
+
|
|
99
|
+
def ask_path(self, question: str, re_ask_reason: Optional[str] = None, *,
|
|
100
|
+
options: Optional[PathAskOptions] = None) -> Optional[Path]:
|
|
101
|
+
"""Ask for a path with a native file or directory picker."""
|
|
102
|
+
path_options = PathAskOptions() if options is None else options
|
|
103
|
+
return self._window_obj().ask_path(question, path_options,
|
|
104
|
+
re_ask_reason)
|
|
105
|
+
|
|
106
|
+
def ask_yes_no(self, question: str, default: bool,
|
|
107
|
+
re_ask_reason: Optional[str] = None) -> bool:
|
|
108
|
+
"""Ask a yes/no question with dedicated yes and no buttons."""
|
|
109
|
+
return self._window_obj().ask_yes_no(question, default, re_ask_reason)
|
|
110
|
+
|
|
111
|
+
def ask_choice(self, question: str, *, choices: Sequence[str],
|
|
112
|
+
default: Optional[str] = None,
|
|
113
|
+
re_ask_reason: Optional[str] = None) -> str:
|
|
114
|
+
"""Ask the user to pick one choice from a single-selection list."""
|
|
115
|
+
return self._window_obj().ask_choice(question, choices, default,
|
|
116
|
+
re_ask_reason)
|
|
117
|
+
|
|
118
|
+
# pylint: disable-next=too-many-arguments
|
|
119
|
+
def ask_multi(self, question: str, *, choices: Sequence[str],
|
|
120
|
+
default: Optional[Sequence[str]] = None, min_select: int = 0,
|
|
121
|
+
max_select: Optional[int] = None,
|
|
122
|
+
re_ask_reason: Optional[str] = None) -> list[str]:
|
|
123
|
+
"""Ask the user to pick several choices from a multi-selection list."""
|
|
124
|
+
return self._window_obj().ask_multi(question, choices, default,
|
|
125
|
+
min_select, max_select,
|
|
126
|
+
re_ask_reason)
|
|
127
|
+
|
|
128
|
+
# pylint: disable-next=too-many-arguments
|
|
129
|
+
def ask_table(self, columns: Sequence[TableColumn],
|
|
130
|
+
cells: list[list[TableCell]], question: str, *,
|
|
131
|
+
re_ask_reason: Optional[str] = None,
|
|
132
|
+
partial_check: Optional[PartialCheck] = None,
|
|
133
|
+
min_rows: Optional[int] = None,
|
|
134
|
+
max_rows: Optional[int] = None) -> list[list[Optional[str]]]:
|
|
135
|
+
"""Ask the user to fill an editable table of the given rows.
|
|
136
|
+
|
|
137
|
+
With both ``min_rows`` and ``max_rows`` given the table has a
|
|
138
|
+
variable number of rows: add-row and remove-row buttons grow the
|
|
139
|
+
table up to ``max_rows`` and shrink it down to ``min_rows``.
|
|
140
|
+
Otherwise the rows given in ``cells`` are fixed and only filled.
|
|
141
|
+
"""
|
|
142
|
+
return self._window_obj().ask_table(columns, cells, question,
|
|
143
|
+
re_ask_reason, partial_check,
|
|
144
|
+
min_rows, max_rows)
|
|
145
|
+
|
|
146
|
+
def ask_form(self, long_question: str, ask_fields: AskFields, *,
|
|
147
|
+
re_ask_reason: Optional[str] = None,
|
|
148
|
+
partial_validator: Optional[PartialFormValidator] = None) \
|
|
149
|
+
-> AnswerFields:
|
|
150
|
+
"""Ask a whole form on one screen; see WizardUiBridge.ask_form."""
|
|
151
|
+
return self._window_obj().ask_form(long_question, ask_fields,
|
|
152
|
+
re_ask_reason, partial_validator)
|
|
153
|
+
|
|
154
|
+
def supports_form_field(self, field: AskField) -> bool:
|
|
155
|
+
"""Report that the Tk form shows every current field type."""
|
|
156
|
+
return handles_field(field)
|
|
157
|
+
|
|
158
|
+
def show(self, message: str) -> None:
|
|
159
|
+
"""Show an informational message to the user."""
|
|
160
|
+
self._window_obj().show(message)
|
|
161
|
+
|
|
162
|
+
def error_file(self) -> TextIO:
|
|
163
|
+
"""Return the stream used for low-level wizard diagnostics."""
|
|
164
|
+
return self._log if self._log is not None else NoTextIO()
|
|
165
|
+
|
|
166
|
+
def close(self) -> None:
|
|
167
|
+
"""Close the wizard window, or clear its area, when one was built."""
|
|
168
|
+
try:
|
|
169
|
+
if self._window is not None:
|
|
170
|
+
self._window.close()
|
|
171
|
+
self._window = None
|
|
172
|
+
finally:
|
|
173
|
+
if self._root is not None:
|
|
174
|
+
self._root.destroy()
|
|
175
|
+
self._root = None
|
|
176
|
+
|
|
177
|
+
def _window_obj(self) -> WizardWindow:
|
|
178
|
+
"""Return the wizard window, building it on first use."""
|
|
179
|
+
if self._window is None:
|
|
180
|
+
self._window = WizardWindow(self._parent, self._area, self._modal)
|
|
181
|
+
return self._window
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
#! /usr/local/bin/python3
|
|
2
|
+
"""A modal month calendar for the Tkinter date and date-time fields.
|
|
3
|
+
|
|
4
|
+
A date field, and the date part of a date-time field, are shown in the
|
|
5
|
+
Tkinter form as a text entry paired with a Pick button. Pressing that
|
|
6
|
+
button, or typing the ``?`` token into the entry, opens this calendar.
|
|
7
|
+
The user steps between months and years and clicks a day to return it;
|
|
8
|
+
Cancel or closing the window returns nothing so the entry keeps its
|
|
9
|
+
value. Days outside a field's inclusive bounds are shown disabled, so the
|
|
10
|
+
calendar only offers acceptable dates.
|
|
11
|
+
|
|
12
|
+
The calendar is event driven: a day or Cancel button calls the picked
|
|
13
|
+
callback and destroys the window. No nested wait loop is entered, so the
|
|
14
|
+
one already running for the wizard host keeps processing events while
|
|
15
|
+
the calendar is open.
|
|
16
|
+
|
|
17
|
+
A modal wizard host holds its own grab, which would otherwise starve this
|
|
18
|
+
separate window of pointer and keyboard events. The calendar therefore
|
|
19
|
+
takes the grab (and the keyboard focus) while it is open, and hands it
|
|
20
|
+
back to the host window when it closes -- but only when that host held a
|
|
21
|
+
grab in the first place, so opening a calendar over a non-modal, embedded
|
|
22
|
+
wizard never makes it modal.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
# Copyright (c) 2026 Tom Björkholm
|
|
26
|
+
# MIT License
|
|
27
|
+
|
|
28
|
+
import calendar
|
|
29
|
+
import tkinter as tk
|
|
30
|
+
from datetime import date
|
|
31
|
+
from functools import partial
|
|
32
|
+
from typing import Callable, Optional
|
|
33
|
+
from wizard_ui_bridge.form_defs import value_out_of_range
|
|
34
|
+
|
|
35
|
+
CALENDAR_TITLE = 'Pick a date'
|
|
36
|
+
WEEKDAYS = ('Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su')
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def month_weeks(year: int, month: int) -> list[list[int]]:
|
|
40
|
+
"""Return the weeks of a month as day numbers, 0 for padding days."""
|
|
41
|
+
return calendar.Calendar().monthdayscalendar(year, month)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def shift_month(year: int, month: int, action: str) -> tuple[int, int]:
|
|
45
|
+
"""Return the year and month reached by one navigation action.
|
|
46
|
+
|
|
47
|
+
This mirrors wizard_ui_bridge._calendar, the private module behind
|
|
48
|
+
the Textual bridge's own calendar screen; that module is not public
|
|
49
|
+
API a sibling package may import, so this one keeps its own copy.
|
|
50
|
+
"""
|
|
51
|
+
# pylint: disable=duplicate-code
|
|
52
|
+
if action == 'prev_year':
|
|
53
|
+
year -= 1
|
|
54
|
+
elif action == 'next_year':
|
|
55
|
+
year += 1
|
|
56
|
+
elif action == 'prev_month':
|
|
57
|
+
year, month = (year, month - 1) if month > 1 else (year - 1, 12)
|
|
58
|
+
else:
|
|
59
|
+
year, month = (year, month + 1) if month < 12 else (year + 1, 1)
|
|
60
|
+
return (min(max(year, date.min.year), date.max.year), month)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def day_out_of_range(day: date, minimum: Optional[date],
|
|
64
|
+
maximum: Optional[date]) -> bool:
|
|
65
|
+
"""Return whether a day lies outside the inclusive date bounds."""
|
|
66
|
+
return value_out_of_range(day, minimum, maximum)
|
|
67
|
+
# pylint: enable=duplicate-code
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _held_grab(widget: tk.Misc) -> bool:
|
|
71
|
+
"""Return whether widget's own window currently holds the app grab."""
|
|
72
|
+
toplevel = widget.winfo_toplevel()
|
|
73
|
+
return toplevel.grab_current() is not None # type: ignore[no-untyped-call]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _restore_grab(widget: Optional[tk.Misc]) -> None:
|
|
77
|
+
"""Give the modal grab back to the widget's window, if it survives."""
|
|
78
|
+
if widget is None or not widget.winfo_exists():
|
|
79
|
+
return
|
|
80
|
+
try:
|
|
81
|
+
widget.winfo_toplevel().grab_set()
|
|
82
|
+
except tk.TclError:
|
|
83
|
+
pass
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
# pylint: disable-next=too-few-public-methods,too-many-instance-attributes
|
|
87
|
+
class CalendarPicker:
|
|
88
|
+
"""A month calendar window returning the date the user clicks."""
|
|
89
|
+
|
|
90
|
+
def __init__(self, parent: tk.Misc, seed: date, minimum: Optional[date],
|
|
91
|
+
maximum: Optional[date],
|
|
92
|
+
on_pick: Callable[[Optional[date]], None]) -> None:
|
|
93
|
+
"""Build the calendar window on the seed month and show it."""
|
|
94
|
+
self._bounds = (minimum, maximum)
|
|
95
|
+
self._on_pick = on_pick
|
|
96
|
+
self._restore = _held_grab(parent)
|
|
97
|
+
self._year = seed.year
|
|
98
|
+
self._month = seed.month
|
|
99
|
+
self._win = tk.Toplevel(parent)
|
|
100
|
+
self._win.title(CALENDAR_TITLE)
|
|
101
|
+
self._win.transient(parent.winfo_toplevel())
|
|
102
|
+
self._win.protocol('WM_DELETE_WINDOW', self._cancel)
|
|
103
|
+
self._win.bind('<Escape>', lambda _event: self._cancel())
|
|
104
|
+
self._title = tk.Label(self._win)
|
|
105
|
+
self._title.pack(pady=4)
|
|
106
|
+
self._add_nav()
|
|
107
|
+
self._grid = tk.Frame(self._win)
|
|
108
|
+
self._grid.pack(padx=6, pady=6)
|
|
109
|
+
tk.Button(self._win, text='Cancel', command=self._cancel).pack(pady=4)
|
|
110
|
+
self._show_month()
|
|
111
|
+
self._grab()
|
|
112
|
+
|
|
113
|
+
def _grab(self) -> None:
|
|
114
|
+
"""Take the modal grab and focus, retrying until the window shows.
|
|
115
|
+
|
|
116
|
+
Grabbing fails while the new window is not yet viewable, so it is
|
|
117
|
+
retried on the wizard's event loop until it succeeds.
|
|
118
|
+
"""
|
|
119
|
+
if not self._win.winfo_exists():
|
|
120
|
+
return
|
|
121
|
+
try:
|
|
122
|
+
self._win.grab_set()
|
|
123
|
+
except tk.TclError:
|
|
124
|
+
self._win.after(50, self._grab)
|
|
125
|
+
return
|
|
126
|
+
self._win.focus_set()
|
|
127
|
+
|
|
128
|
+
def _add_nav(self) -> None:
|
|
129
|
+
"""Add the previous and next month and year navigation buttons."""
|
|
130
|
+
box = tk.Frame(self._win)
|
|
131
|
+
box.pack()
|
|
132
|
+
for text, action in (('<< year', 'prev_year'), ('< month',
|
|
133
|
+
'prev_month'), ('month >', 'next_month'),
|
|
134
|
+
('year >>', 'next_year')):
|
|
135
|
+
tk.Button(box, text=text,
|
|
136
|
+
command=partial(self._navigate, action)).pack(
|
|
137
|
+
side='left', padx=2)
|
|
138
|
+
|
|
139
|
+
def _navigate(self, action: str) -> None:
|
|
140
|
+
"""Move the shown month by one navigation action and redraw."""
|
|
141
|
+
self._year, self._month = shift_month(self._year, self._month, action)
|
|
142
|
+
self._show_month()
|
|
143
|
+
|
|
144
|
+
def _show_month(self) -> None:
|
|
145
|
+
"""Show the current month's title and rebuild the day grid."""
|
|
146
|
+
self._title.configure(text=f'{calendar.month_name[self._month]} '
|
|
147
|
+
f'{self._year}')
|
|
148
|
+
for child in self._grid.winfo_children():
|
|
149
|
+
child.destroy()
|
|
150
|
+
for column, name in enumerate(WEEKDAYS):
|
|
151
|
+
tk.Label(self._grid, text=name).grid(row=0, column=column, padx=1)
|
|
152
|
+
self._place_days()
|
|
153
|
+
|
|
154
|
+
def _place_days(self) -> None:
|
|
155
|
+
"""Place one day button, or a blank cell, per day of the month."""
|
|
156
|
+
for week, days in enumerate(month_weeks(self._year, self._month), 1):
|
|
157
|
+
for column, day in enumerate(days):
|
|
158
|
+
self._day_widget(day).grid(row=week, column=column, padx=1,
|
|
159
|
+
pady=1)
|
|
160
|
+
|
|
161
|
+
def _day_widget(self, day: int) -> tk.Widget:
|
|
162
|
+
"""Return a blank cell for a padding day, else a day button."""
|
|
163
|
+
if day == 0:
|
|
164
|
+
return tk.Label(self._grid, text='')
|
|
165
|
+
button = tk.Button(self._grid, text=str(day), width=2,
|
|
166
|
+
command=partial(self._pick, day))
|
|
167
|
+
minimum, maximum = self._bounds
|
|
168
|
+
if day_out_of_range(date(self._year, self._month, day), minimum,
|
|
169
|
+
maximum):
|
|
170
|
+
button['state'] = 'disabled'
|
|
171
|
+
return button
|
|
172
|
+
|
|
173
|
+
def _pick(self, day: int) -> None:
|
|
174
|
+
"""Return the clicked day's date and close the calendar."""
|
|
175
|
+
self._finish(date(self._year, self._month, day))
|
|
176
|
+
|
|
177
|
+
def _cancel(self) -> None:
|
|
178
|
+
"""Close the calendar without returning a date."""
|
|
179
|
+
self._finish(None)
|
|
180
|
+
|
|
181
|
+
def _finish(self, chosen: Optional[date]) -> None:
|
|
182
|
+
"""Report the outcome, destroy the window and restore the grab."""
|
|
183
|
+
parent = self._win.master
|
|
184
|
+
try:
|
|
185
|
+
self._on_pick(chosen)
|
|
186
|
+
finally:
|
|
187
|
+
self._win.destroy()
|
|
188
|
+
if self._restore:
|
|
189
|
+
_restore_grab(parent)
|