pygui_simple 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.
@@ -0,0 +1,448 @@
1
+ # !/usr/bin/python3
2
+ # -*- coding: UTF-8 -*-
3
+ import tkinter as tk
4
+ from typing import Callable, cast, override
5
+
6
+ from pygui.winbasic import Dialog
7
+ from pygui.tkcontrol import tkControl
8
+
9
+
10
+ class SlideSwitchCtrl(tkControl):
11
+ """iOS-style toggle switch widget implemented with Tkinter Canvas.
12
+
13
+ This widget replicates the behavior and appearance of the native iOS toggle switch,
14
+ supporting both click-to-toggle and drag-to-toggle interactions. The switch state
15
+ is visually synchronized with its logical state, and smooth animation is provided
16
+ for state transitions.
17
+
18
+ Key Features:
19
+ - Click anywhere on the switch to toggle state instantly
20
+ - Drag the slider to adjust position and release to confirm state
21
+ - Smooth animation for state transitions
22
+ - Customizable colors for on/off states, slider, and slider shadow
23
+ - Callback function triggered on state change
24
+
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ parent: tk.Misc,
30
+ owner: Dialog,
31
+ idself: str,
32
+ width: int = 80,
33
+ height: int = 40,
34
+ default_state: bool = False,
35
+ on_color: str = "#007AFF",
36
+ off_color: str = "#E5E5E5",
37
+ slider_color: str = "white",
38
+ slider_shadow: str = "#CCCCCC",
39
+ callback: Callable[[bool], None] | None = None
40
+ ) -> None:
41
+ """Initialize the SlideSwitch widget.
42
+
43
+ Args:
44
+ parent: Parent Tkinter widget (e.g., Tk, Frame, Canvas) that contains this switch
45
+ owner: message to deliver
46
+ idself: id of control self
47
+ width: Width of the switch in pixels (default: 80)
48
+ height: Height of the switch in pixels (default: 40)
49
+ default_state: Initial state of the switch (False = off, True = on; default: False)
50
+ on_color: Background color when switch is in on state (default: iOS blue "#007AFF")
51
+ off_color: Background color when switch is in off state (default: iOS gray "#E5E5E5")
52
+ slider_color: Color of the slider button (default: white)
53
+ slider_shadow: Color of the slider's drop shadow (default: light gray "#CCCCCC")
54
+ callback: Optional function to call when switch state changes. The function
55
+ should accept a single boolean parameter representing the new state.
56
+
57
+ Returns:
58
+ None
59
+ """
60
+ ctrl = tk.Canvas(parent, width=width, height=height, highlightthickness=0)
61
+ super().__init__(parent, "", idself, ctrl)
62
+ self._master: Dialog = owner
63
+
64
+ self._width: int = width
65
+ self._height: int = height
66
+ self._state: bool = default_state
67
+ self._on_color: str = on_color
68
+ self._off_color: str = off_color
69
+ self._slider_color: str = slider_color
70
+ self._slider_shadow: str = slider_shadow
71
+ self._callback: Callable[[bool], None] | None = callback
72
+
73
+ self._radius: int = height // 2 # Radius for rounded switch corners
74
+ self._slider_padding: int = 2 # Padding between slider and switch border
75
+ self._drag_threshold: int = 3 # Pixel threshold to distinguish click vs drag
76
+ self._is_dragging: bool = False # Flag to track drag state
77
+ self._start_x: int = 0 # Starting X coordinate of mouse press
78
+ self._current_slider_x: float = 0.0 # Current X position of slider (supports animation)
79
+ self._original_slider_x: float = 0.0 # Original slider position before drag
80
+
81
+ # Private instance variables (core implementation details, not accessible externally)
82
+ self.__slider_size: int = self._height - 2 * self._slider_padding # Diameter of slider
83
+ self.__slider_off_x: int = self._slider_padding # X position of slider in off state
84
+ self.__slider_on_x: int = self._width - self.__slider_size - self._slider_padding # X position in on state
85
+
86
+ # Initialize slider position based on default state
87
+ self._current_slider_x = float(self.__slider_off_x) if not default_state else float(self.__slider_on_x)
88
+
89
+ # Initial render and event binding
90
+ self._redraw_all()
91
+ self._bind_events()
92
+
93
+ def _redraw_all(self) -> None:
94
+ """Redraw the entire switch widget (background + slider).
95
+
96
+ Clears the canvas and redraws all elements to ensure visual consistency
97
+ with the current state. Called on every state change or drag movement.
98
+
99
+ Returns:
100
+ None
101
+ """
102
+ canvas = cast(tk.Canvas, self._tkctrl)
103
+ canvas.delete("all")
104
+
105
+ # Draw switch background (rounded rectangle)
106
+ bg_color: str = self._on_color if self._state else self._off_color
107
+ self._draw_rounded_rect(0, 0, self._width, self._height, self._radius, bg_color)
108
+
109
+ # Draw slider shadow (slightly offset for depth effect)
110
+ shadow_x: float = self._current_slider_x - 1
111
+ shadow_y: int = self._slider_padding - 1
112
+ _ = canvas.create_oval(
113
+ shadow_x, shadow_y,
114
+ shadow_x + self.__slider_size + 2,
115
+ shadow_y + self.__slider_size + 2,
116
+ fill=self._slider_shadow,
117
+ outline=""
118
+ )
119
+
120
+ # Draw main slider button
121
+ _ = canvas.create_oval(
122
+ self._current_slider_x, self._slider_padding,
123
+ self._current_slider_x + self.__slider_size,
124
+ self._slider_padding + self.__slider_size,
125
+ fill=self._slider_color,
126
+ outline=""
127
+ )
128
+
129
+ def _draw_rounded_rect(
130
+ self,
131
+ x1: int,
132
+ y1: int,
133
+ x2: int,
134
+ y2: int,
135
+ radius: int,
136
+ fill: str
137
+ ) -> None:
138
+ """Draw a rounded rectangle on the canvas.
139
+
140
+ Creates a rectangle with fully rounded corners (pill shape) by combining
141
+ arc segments and rectangles. This matches the native iOS switch appearance.
142
+
143
+ Args:
144
+ x1: Top-left X coordinate of the rectangle
145
+ y1: Top-left Y coordinate of the rectangle
146
+ x2: Bottom-right X coordinate of the rectangle
147
+ y2: Bottom-right Y coordinate of the rectangle
148
+ radius: Radius of the rounded corners (should be half the height for pill shape)
149
+ fill: Background color of the rounded rectangle
150
+
151
+ Returns:
152
+ None
153
+ """
154
+ canvas = cast(tk.Canvas, self._tkctrl)
155
+
156
+ # Draw four rounded corners (arcs)
157
+ _ = canvas.create_arc(
158
+ x1, y1, x1 + 2 * radius, y1 + 2 * radius,
159
+ start=90, extent=90, fill=fill, outline=fill, width=0
160
+ )
161
+ _ = canvas.create_arc(
162
+ x2 - 2 * radius, y1, x2, y1 + 2 * radius,
163
+ start=0, extent=90, fill=fill, outline=fill, width=0
164
+ )
165
+ _ = canvas.create_arc(
166
+ x1, y2 - 2 * radius, x1 + 2 * radius, y2,
167
+ start=180, extent=90, fill=fill, outline=fill, width=0
168
+ )
169
+ _ = canvas.create_arc(
170
+ x2 - 2 * radius, y2 - 2 * radius, x2, y2,
171
+ start=270, extent=90, fill=fill, outline=fill, width=0
172
+ )
173
+
174
+ # Fill the middle areas between arcs
175
+ _ = canvas.create_rectangle(
176
+ x1 + radius, y1, x2 - radius, y2,
177
+ fill=fill, outline=fill, width=0
178
+ )
179
+ _ = canvas.create_rectangle(
180
+ x1, y1 + radius, x2, y2 - radius,
181
+ fill=fill, outline=fill, width=0
182
+ )
183
+
184
+ def _bind_events(self) -> None:
185
+ """Bind mouse events to handle user interactions.
186
+
187
+ Binds press, drag, and release events to their respective handlers
188
+ to manage click and drag interactions with the switch.
189
+
190
+ Returns:
191
+ None
192
+ """
193
+ _ = self._tkctrl.bind("<ButtonPress-1>", self._on_press)
194
+ _ = self._tkctrl.bind("<B1-Motion>", self._on_drag)
195
+ _ = self._tkctrl.bind("<ButtonRelease-1>", self._on_release)
196
+
197
+ def _on_press(self, event: tk.Event) -> None:
198
+ """Handle mouse press event on the switch.
199
+
200
+ Initializes drag state tracking and records the starting position
201
+ of the mouse press and slider.
202
+
203
+ Args:
204
+ event: Tkinter mouse event object containing press coordinates
205
+
206
+ Returns:
207
+ None
208
+ """
209
+ self._is_dragging = False
210
+ self._start_x = event.x
211
+ self._original_slider_x = self._current_slider_x
212
+
213
+ def _on_drag(self, event: tk.Event) -> None:
214
+ """Handle mouse drag event on the switch.
215
+
216
+ Updates the slider position in real-time during drag operations,
217
+ limits movement to valid bounds, and updates the visual state
218
+ to reflect the current slider position.
219
+
220
+ Args:
221
+ event: Tkinter mouse event object containing drag coordinates
222
+
223
+ Returns:
224
+ None
225
+ """
226
+ delta_x: int = event.x - self._start_x
227
+
228
+ # Determine if movement exceeds drag threshold (distinguish click vs drag)
229
+ if abs(delta_x) > self._drag_threshold:
230
+ self._is_dragging = True
231
+
232
+ if self._is_dragging:
233
+ # Calculate new slider position with boundary limits
234
+ new_x: float = self._original_slider_x + delta_x
235
+ self._current_slider_x = max(
236
+ float(self.__slider_off_x),
237
+ min(new_x, float(self.__slider_on_x))
238
+ )
239
+
240
+ # Update logical state based on slider position (50% threshold)
241
+ ratio: float = (self._current_slider_x - self.__slider_off_x) / (self.__slider_on_x - self.__slider_off_x)
242
+ self._state = ratio > 0.5
243
+
244
+ # Redraw to reflect new position/state
245
+ self._redraw_all()
246
+
247
+ def _on_release(self, event: tk.Event) -> None:
248
+ """Handle mouse release event on the switch.
249
+
250
+ Determines the final state based on whether the interaction was a click
251
+ or drag, then animates the slider to the final position and triggers
252
+ the callback if the state changed.
253
+
254
+ Args:
255
+ event: Tkinter mouse event object containing release coordinates
256
+
257
+ Returns:
258
+ None
259
+ """
260
+ new_state: bool = False
261
+ if self._is_dragging:
262
+ # For drag interactions: determine state from final slider position
263
+ ratio: float = (self._current_slider_x - self.__slider_off_x) / (self.__slider_on_x - self.__slider_off_x)
264
+ new_state = ratio > 0.5
265
+ else:
266
+ # For click interactions: toggle state directly
267
+ new_state = not self._state
268
+
269
+ # Animate to final state and trigger callback if needed
270
+ self._animate_to_state(new_state)
271
+
272
+ def _animate_to_state(self, target_state: bool) -> None:
273
+ """Animate the slider to the target state position.
274
+
275
+ Provides smooth linear animation from current position to the target
276
+ position (on/off). Triggers the callback function if the state changes.
277
+
278
+ Args:
279
+ target_state: Desired final state (False = off, True = on)
280
+
281
+ Returns:
282
+ None
283
+ """
284
+ # Calculate target position based on desired state
285
+ target_x: float = float(self.__slider_on_x) if target_state else float(self.__slider_off_x)
286
+ distance: float = target_x - self._current_slider_x
287
+
288
+ # If already at target position (within 1px tolerance), finalize state
289
+ if abs(distance) < 1:
290
+ self._current_slider_x = target_x
291
+ self._redraw_all()
292
+
293
+ self._on_state_changed(target_state)
294
+ return
295
+
296
+ # Calculate animation step (smooth movement over 10 frames)
297
+ step = distance / 10 if abs(distance) > 10 else (1.0 if distance > 0 else -1.0)
298
+
299
+ # Recursive animation function (executes every 8ms for ~60fps)
300
+ def animate_step() -> None:
301
+ nonlocal step, target_x
302
+ self._current_slider_x += step
303
+
304
+ # Check if animation has reached target position
305
+ if ((step > 0 and self._current_slider_x >= target_x) or
306
+ (step < 0 and self._current_slider_x <= target_x)):
307
+ self._current_slider_x = target_x
308
+
309
+ self._on_state_changed(target_state)
310
+ self._redraw_all()
311
+ return
312
+
313
+ # Continue animation loop
314
+ self._redraw_all()
315
+ _ = self._tkctrl.after(8, animate_step)
316
+
317
+ # Start animation sequence
318
+ animate_step()
319
+
320
+ def get_state(self) -> bool:
321
+ """Get the current logical state of the switch.
322
+
323
+ This is the public API method to retrieve the switch state, preferred
324
+ over direct access to the state attribute for API consistency.
325
+
326
+ Returns:
327
+ bool: Current state (True = on, False = off)
328
+ """
329
+ return self._state
330
+
331
+ def set_state(self, state: bool, animate: bool = True) -> None:
332
+ """Set the switch to a specific state programmatically.
333
+
334
+ set the switch state with optional animation.
335
+ Triggers the callback function if the state changes.
336
+
337
+ Args:
338
+ state: Desired state (True = on, False = off)
339
+ animate: Whether to animate the transition (default: True)
340
+
341
+ Returns:
342
+ None
343
+ """
344
+ # Exit if no state change needed
345
+ if state == self._state:
346
+ return
347
+
348
+ # Animate to new state or set directly
349
+ if animate:
350
+ self._animate_to_state(state)
351
+ else:
352
+ # Set position directly without animation
353
+ self._current_slider_x = float(self.__slider_on_x) if state else float(self.__slider_off_x)
354
+ self._redraw_all()
355
+
356
+ self._on_state_changed(state)
357
+
358
+ def _on_state_changed(self, state: bool):
359
+ self._state = state
360
+ # Trigger callback if state changed
361
+ if self._callback:
362
+ self._callback(state)
363
+ _ = self._master.process_message(self._idself, event="Changed", val=state)
364
+
365
+
366
+ if __name__ == "__main__":
367
+ class tkBasic(Dialog):
368
+ """Demonstration application for the SlideSwitch widget.
369
+
370
+ Creates a simple Tkinter window with the SlideSwitch widget,
371
+ status display, and test button to verify functionality.
372
+
373
+ """
374
+ def __init__(self, title: str, w: int, h: int):
375
+ super().__init__(title, w, h)
376
+ self._root: tk.Tk = tk.Tk()
377
+ self._root.title(title)
378
+ self._root.geometry(f"{w}x{h}")
379
+ _ = self._root.configure(bg="#F5F5F7") # iOS system background color
380
+
381
+ # create ui
382
+
383
+ # Title label
384
+ title_label: tk.Label = tk.Label(
385
+ self._root,
386
+ text=title,
387
+ bg="#F5F5F7",
388
+ font=("SF Pro Text", 18, "bold")
389
+ )
390
+ title_label.pack(pady=30)
391
+
392
+ # Create SlideSwitch widget
393
+ self._switch: SlideSwitchCtrl = SlideSwitchCtrl(
394
+ self._root,
395
+ self,
396
+ "",
397
+ width=80,
398
+ height=40,
399
+ default_state=False,
400
+ slider_color="white",
401
+ slider_shadow="#CCCCCC",
402
+ callback=self.on_switch_change
403
+ )
404
+ self._switch.control.pack(pady=20)
405
+
406
+ # Status color block (visual state indicator)
407
+ self._status_block: tk.Label = tk.Label(
408
+ self._root,
409
+ text="",
410
+ bg="#E5E5E5",
411
+ width=10,
412
+ height=2,
413
+ bd=0,
414
+ relief="flat"
415
+ )
416
+ self._status_block.pack(pady=10)
417
+
418
+ # Status text label
419
+ self._status_label: tk.Label = tk.Label(
420
+ self._root,
421
+ text="Current State: ❌ Off",
422
+ bg="#F5F5F7",
423
+ font=("SF Pro Text", 14)
424
+ )
425
+ self._status_label.pack(pady=10)
426
+
427
+ def on_switch_change(self, state: bool) -> None:
428
+ """Callback function to update status display on state change.
429
+
430
+ Args:
431
+ state: New state of the switch (True = on, False = off)
432
+
433
+ Returns:
434
+ None
435
+ """
436
+ _ = self._status_label.config(text=f"Current State: {'✅ On' if state else '❌ Off'}")
437
+ _ = self._status_block.config(bg="#007AFF" if state else "#E5E5E5")
438
+
439
+ def go(self):
440
+ # Start main event loop
441
+ self._root.mainloop()
442
+
443
+ @override
444
+ def destroy(self, **kwargs: object):
445
+ super().destroy(**kwargs)
446
+
447
+ gui = tkBasic("iOS Style Toggle Switch", 400, 350)
448
+ gui.go()