CTkMVC 0.1.0__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.
ctkmvc/__init__.py ADDED
@@ -0,0 +1,20 @@
1
+ """Active MVC building blocks for CustomTkinter."""
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from .controller import BaseController
6
+ from .model import BaseModel
7
+
8
+ if TYPE_CHECKING:
9
+ from .view import BaseView
10
+
11
+ __all__ = ["BaseController", "BaseModel", "BaseView"]
12
+
13
+
14
+ def __getattr__(name: str):
15
+ if name == "BaseView":
16
+ from .view import BaseView
17
+
18
+ globals()[name] = BaseView
19
+ return BaseView
20
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
ctkmvc/controller.py ADDED
@@ -0,0 +1,32 @@
1
+ """Controllers with explicit constructor injection."""
2
+
3
+ from abc import ABC, abstractmethod
4
+ from typing import Generic, TypeVar
5
+
6
+ from .model import ModelT
7
+
8
+ ViewT = TypeVar("ViewT")
9
+
10
+
11
+ class BaseController(ABC, Generic[ModelT, ViewT]):
12
+ """Connect user actions to model operations.
13
+
14
+ Override bind_actions and call it after construction to connect the UI.
15
+ Views can be replaced by test doubles without constructing a window.
16
+ """
17
+
18
+ def __init__(self, model: ModelT, view: ViewT) -> None:
19
+ self._model = model
20
+ self._view = view
21
+
22
+ @property
23
+ def model(self) -> ModelT:
24
+ return self._model
25
+
26
+ @property
27
+ def view(self) -> ViewT:
28
+ return self._view
29
+
30
+ @abstractmethod
31
+ def bind_actions(self) -> None:
32
+ """Connect widget commands to controller methods."""
ctkmvc/model.py ADDED
@@ -0,0 +1,37 @@
1
+ """Observable models independent of the GUI."""
2
+
3
+ from collections.abc import Callable
4
+ from typing import Any, Generic, TypeVar
5
+
6
+ EventT = TypeVar("EventT")
7
+
8
+
9
+ class BaseModel(Generic[EventT]):
10
+ """Publish typed events synchronously after changing model state."""
11
+
12
+ def __init__(self) -> None:
13
+ self._observers: dict[object, Callable[[EventT], None]] = {}
14
+
15
+ def subscribe(self, observer: Callable[[EventT], None]) -> Callable[[], None]:
16
+ """Register an observer and return an idempotent unsubscribe function."""
17
+ token = object()
18
+ self._observers[token] = observer
19
+
20
+ def unsubscribe() -> None:
21
+ self._observers.pop(token, None)
22
+
23
+ return unsubscribe
24
+
25
+ def notify(self, event: EventT) -> None:
26
+ """Notify in registration order on the calling thread.
27
+
28
+ New subscriptions take effect on the next notification. Removed
29
+ subscriptions are skipped. Exceptions from observers propagate.
30
+ """
31
+ for token in tuple(self._observers):
32
+ observer = self._observers.get(token)
33
+ if observer is not None:
34
+ observer(event)
35
+
36
+
37
+ ModelT = TypeVar("ModelT", bound=BaseModel[Any])
ctkmvc/py.typed ADDED
File without changes
ctkmvc/view.py ADDED
@@ -0,0 +1,51 @@
1
+ """CustomTkinter views that observe a model directly."""
2
+
3
+ from abc import ABC, abstractmethod
4
+ from collections.abc import Callable
5
+ from typing import Any, Generic
6
+
7
+ import customtkinter as ctk
8
+
9
+ from .model import EventT, ModelT
10
+
11
+
12
+ class BaseView(ctk.CTkFrame, ABC, Generic[ModelT, EventT]):
13
+ """A frame with automatic model subscription and cleanup.
14
+
15
+ Override build and render. Both run during construction, so initialize
16
+ any extra dependencies before calling super().__init__().
17
+ """
18
+
19
+ def __init__(self, master: Any, model: ModelT, **kwargs: Any) -> None:
20
+ super().__init__(master, **kwargs)
21
+ self._model = model
22
+ self._unsubscribe: Callable[[], None] | None = None
23
+ try:
24
+ self.build()
25
+ self._unsubscribe = model.subscribe(self.on_model_changed)
26
+ self.render()
27
+ except BaseException:
28
+ self.destroy()
29
+ raise
30
+
31
+ @property
32
+ def model(self) -> ModelT:
33
+ return self._model
34
+
35
+ @abstractmethod
36
+ def build(self) -> None:
37
+ """Create and lay out child widgets."""
38
+
39
+ @abstractmethod
40
+ def render(self) -> None:
41
+ """Read current model state and update existing widgets."""
42
+
43
+ def on_model_changed(self, event: EventT) -> None:
44
+ """Refresh the view; override for event-specific updates."""
45
+ self.render()
46
+
47
+ def destroy(self) -> None:
48
+ if self._unsubscribe is not None:
49
+ self._unsubscribe()
50
+ self._unsubscribe = None
51
+ super().destroy()
@@ -0,0 +1,269 @@
1
+ Metadata-Version: 2.3
2
+ Name: ctkmvc
3
+ Version: 0.1.0
4
+ Summary: Active MVC building blocks for CustomTkinter applications
5
+ Author: Ivan Kirov
6
+ Author-email: Ivan Kirov <evankirk@vk.com>
7
+ Requires-Dist: customtkinter>=5.2.2,<6
8
+ Requires-Python: >=3.14
9
+ Description-Content-Type: text/markdown
10
+
11
+ # ctkmvc
12
+
13
+ ![Python](https://img.shields.io/badge/Python-3.14%2B-blue)
14
+ ![CustomTkinter](https://img.shields.io/badge/CustomTkinter-5.2.2%2B-blue)
15
+ ![Version](https://img.shields.io/badge/version-0.1.0-green)
16
+
17
+ **Lightweight Active MVC building blocks for [CustomTkinter](https://github.com/TomSchimansky/CustomTkinter) applications.**
18
+
19
+ ctkmvc provides reusable, typed base classes for separating application state, graphical interfaces, and user interaction logic. Instead of manually synchronizing widgets with application state, views subscribe to model events and update automatically when the model publishes a change.
20
+
21
+ ## Features
22
+
23
+ - Active Model–View–Controller architecture with synchronous model notifications.
24
+ - Typed events and generic base classes for models, views, and controllers.
25
+ - Explicit constructor dependency injection without a container or global registry.
26
+ - Automatic view subscription, initial rendering, and subscription cleanup.
27
+ - Multiple views observing the same model.
28
+ - Compatibility with standard CustomTkinter frame layouts and configuration options.
29
+ - Model and controller testing without a graphical environment or Tkinter.
30
+
31
+ ## Architecture
32
+
33
+ ```mermaid
34
+ flowchart LR
35
+ User -->|Interaction| View
36
+ View -->|Widget command| Controller
37
+ Controller -->|Domain operation| Model
38
+ Model -->|Change notification| View
39
+ ```
40
+
41
+ | Component | Responsibility |
42
+ | --- | --- |
43
+ | Model | Owns application state and domain logic; publishes events after changes. |
44
+ | View | Creates widgets and renders model state. |
45
+ | Controller | Connects user actions to model operations. |
46
+
47
+ Unlike passive MVC, the controller does not need to refresh the view after each operation. Changes initiated by other components also reach subscribed views, provided the model publishes an event.
48
+
49
+ The library uses the **Observer** pattern for notifications, **Template Method** for view initialization, and **Dependency Injection** for component dependencies. The application entry point serves as the **Composition Root**, where components are created and connected explicitly.
50
+
51
+ ## Installation
52
+
53
+ ### Requirements
54
+
55
+ - Python 3.14 or newer.
56
+ - CustomTkinter >= 5.2.2, < 6 (installed automatically as a dependency).
57
+ - Tkinter and Tcl/Tk for graphical applications.
58
+
59
+ Tkinter is a Python standard library module with native dependencies. If it is missing, install it using your operating system's package manager for the Python interpreter you use:
60
+
61
+ | Distribution | Command |
62
+ | --- | --- |
63
+ | Fedora | `sudo dnf install python3-tkinter` |
64
+ | Arch Linux | `sudo pacman -S tk` |
65
+ | Debian / Ubuntu | `sudo apt install python3-tk` |
66
+
67
+ Package names may vary for separately installed Python versions. Verify Tkinter with `python -m tkinter` (or `uv run python -m tkinter` inside a uv project).
68
+
69
+ ### From a local checkout
70
+
71
+ Run from the ctkmvc repository root:
72
+
73
+ ```sh
74
+ uv sync
75
+ uv run python examples/counter.py
76
+ ```
77
+
78
+ To install a local checkout as a dependency of another project:
79
+
80
+ ```sh
81
+ uv add /path/to/ctkmvc
82
+ ```
83
+
84
+ Alternatively, with pip and a compatible Python environment:
85
+
86
+ ```sh
87
+ python -m pip install /path/to/ctkmvc
88
+ ```
89
+
90
+ ## Quick start
91
+
92
+ The following complete example implements a counter with a typed domain event. Save it as `main.py` in a project with ctkmvc installed and run `uv run python main.py`.
93
+
94
+ ```python
95
+ from dataclasses import dataclass
96
+
97
+ import customtkinter as ctk
98
+
99
+ from ctkmvc import BaseController, BaseModel, BaseView
100
+
101
+
102
+ @dataclass(frozen=True)
103
+ class CountChanged:
104
+ value: int
105
+
106
+
107
+ class CounterModel(BaseModel[CountChanged]):
108
+ def __init__(self) -> None:
109
+ super().__init__()
110
+ self._count = 0
111
+
112
+ @property
113
+ def count(self) -> int:
114
+ return self._count
115
+
116
+ def increment(self) -> None:
117
+ self._count += 1
118
+ self.notify(CountChanged(self._count))
119
+
120
+
121
+ class CounterView(BaseView[CounterModel, CountChanged]):
122
+ def build(self) -> None:
123
+ self.label = ctk.CTkLabel(self, text="")
124
+ self.label.pack(padx=20, pady=10)
125
+ self.button = ctk.CTkButton(self, text="+1")
126
+ self.button.pack(padx=20, pady=10)
127
+
128
+ def render(self) -> None:
129
+ self.label.configure(text=str(self.model.count))
130
+
131
+
132
+ class CounterController(BaseController[CounterModel, CounterView]):
133
+ def bind_actions(self) -> None:
134
+ self.view.button.configure(command=self.increment)
135
+
136
+ def increment(self) -> None:
137
+ self.model.increment()
138
+
139
+
140
+ def main() -> None:
141
+ root = ctk.CTk()
142
+ root.title("Active MVC counter")
143
+
144
+ model = CounterModel()
145
+ view = CounterView(root, model)
146
+ view.pack(padx=20, pady=20)
147
+ controller = CounterController(model, view)
148
+ controller.bind_actions()
149
+
150
+ # Changes outside the controller also update the view.
151
+ root.after(1000, model.increment)
152
+ root.mainloop()
153
+
154
+
155
+ if __name__ == "__main__":
156
+ main()
157
+ ```
158
+
159
+ The initial counter value is rendered during view construction. Clicking the button invokes the controller, which changes the model. The model publishes `CountChanged`, and the view refreshes automatically. The scheduled increment demonstrates that changes outside the controller work the same way.
160
+
161
+ See also [examples/counter.py](examples/counter.py).
162
+
163
+ ## Public API
164
+
165
+ All three base classes are available directly from `ctkmvc`.
166
+
167
+ ### `BaseModel[EventT]`
168
+
169
+ An observable base class with no GUI dependencies. Subclasses define their own state, validation, and domain operations.
170
+
171
+ | Method | Description |
172
+ | --- | --- |
173
+ | `__init__()` | Initializes the observer registry. Call it from subclass constructors. |
174
+ | `subscribe(observer)` | Registers a callback accepting an event and returns an unsubscribe function. |
175
+ | `notify(event)` | Delivers an event to current observers synchronously. |
176
+
177
+ Manual subscriptions are useful for logging, testing, or other non-GUI consumers:
178
+
179
+ ```python
180
+ model = CounterModel()
181
+ unsubscribe = model.subscribe(lambda event: print(event.value))
182
+ model.increment() # Prints 1
183
+ unsubscribe()
184
+ model.increment() # No notification to the removed observer
185
+ ```
186
+
187
+ Calling the returned unsubscribe function repeatedly is safe. Each subscription is independent. Observers are called in registration order; subscriptions added during delivery take effect on the next notification, and removed subscriptions are skipped. Exceptions propagate to the caller and interrupt delivery.
188
+
189
+ ### `BaseView[ModelT, EventT]`
190
+
191
+ An abstract subclass of `customtkinter.CTkFrame`. The constructor accepts `master`, `model`, and additional frame keyword arguments.
192
+
193
+ | Member | Description |
194
+ | --- | --- |
195
+ | `model` | Read-only property exposing the injected model. |
196
+ | `build()` | Required override. Creates and lays out child widgets. |
197
+ | `render()` | Required override. Updates existing widgets from current model state. |
198
+ | `on_model_changed(event)` | Calls `render()` by default; override for event-specific updates. |
199
+ | `destroy()` | Unsubscribes from the model and destroys the frame. |
200
+
201
+ The base constructor calls `build()`, subscribes to the model, and calls `render()`. Initialize any additional dependencies before calling `super().__init__()`.
202
+
203
+ Several views can share a single model:
204
+
205
+ ```python
206
+ model = CounterModel()
207
+ first = CounterView(root, model)
208
+ second = CounterView(root, model)
209
+ first.pack()
210
+ second.pack()
211
+ model.increment() # Both views refresh.
212
+ ```
213
+
214
+ ### `BaseController[ModelT, ViewT]`
215
+
216
+ An abstract controller with explicit model and view dependencies. It does not require a specific widget class, allowing a test double to replace the real view.
217
+
218
+ | Member | Description |
219
+ | --- | --- |
220
+ | `__init__(model, view)` | Stores injected dependencies. |
221
+ | `model` | Read-only property exposing the model. |
222
+ | `view` | Read-only property exposing the view. |
223
+ | `bind_actions()` | Required override. Connects widget commands or other actions to controller methods. |
224
+
225
+ Call `bind_actions()` explicitly after construction. Additional dependencies, such as repositories or application services, can be passed through subclass constructors. Keep domain rules in the model or domain services rather than in widget callbacks.
226
+
227
+ ## Lifecycle and threading
228
+
229
+ - Publish events explicitly after updating model state. Assigning an attribute alone does not trigger a notification.
230
+ - Notifications execute synchronously on the calling thread. Models observed by views must be updated on the Tk GUI thread.
231
+ - For background work, transfer results to the GUI thread, for example through a queue polled using Tk's `after()` method. Automatic cross-thread dispatch is not provided.
232
+ - Destroy a view or its parent to release its automatic model subscription. Hiding a frame does not unsubscribe it.
233
+ - If overriding `destroy()`, call the base implementation. For manual subscriptions, retain and invoke the unsubscribe function when it is no longer needed.
234
+
235
+ ## Development
236
+
237
+ ```text
238
+ src/ctkmvc/
239
+ __init__.py Public API
240
+ model.py Observable model
241
+ view.py CustomTkinter view lifecycle
242
+ controller.py Controller dependencies
243
+ py.typed Typing marker
244
+ examples/
245
+ counter.py Complete Active MVC example
246
+ tests/
247
+ test_mvc.py Unit and integration tests
248
+ ```
249
+
250
+ Install dependencies and run the test suite:
251
+
252
+ ```sh
253
+ uv sync
254
+ uv run python -m unittest discover -s tests -v
255
+ ```
256
+
257
+ Model and controller tests run without Tkinter. View lifecycle tests require Tkinter, and the real-widget integration test also requires a display. Tests with unavailable GUI prerequisites are skipped.
258
+
259
+ Build source and wheel distributions:
260
+
261
+ ```sh
262
+ uv build
263
+ ```
264
+
265
+ The generated distributions are placed in `dist/`.
266
+
267
+ ## Project status
268
+
269
+ ctkmvc is currently at version 0.1.0 and provides the core building blocks of Active MVC. It does not prescribe application navigation, persistence, asynchronous execution, or a dependency injection container.
@@ -0,0 +1,8 @@
1
+ ctkmvc/__init__.py,sha256=ochF1GKf36evnUCdnNV23tSNUGVKBujdWa-3R8GWMl8,487
2
+ ctkmvc/controller.py,sha256=8E6Y-Cc318JSWmBA78QvROFgaVop1Zwg2rmlP8ilO2E,816
3
+ ctkmvc/model.py,sha256=cAqqOhR07nqcLrLtUZFwR6BO0H7Me1ZHP4LjMaLpAbs,1188
4
+ ctkmvc/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ ctkmvc/view.py,sha256=DTLQJS6qgwueaum7WuzExcY_vAKozdHnadi4QmFHakg,1519
6
+ ctkmvc-0.1.0.dist-info/WHEEL,sha256=MWx7psoF7KNST9G72pGtiBYuaXRXQXBk9pw5R6FzYko,80
7
+ ctkmvc-0.1.0.dist-info/METADATA,sha256=j9HSy5Vda8luaLExe6dTv235lKWeYv0VjEoR98ARFTg,10024
8
+ ctkmvc-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.7
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any