pygui_simple 0.5.2__tar.gz → 0.6.0__tar.gz

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.
Files changed (42) hide show
  1. {pygui_simple-0.5.2 → pygui_simple-0.6.0}/PKG-INFO +2 -1
  2. {pygui_simple-0.5.2 → pygui_simple-0.6.0}/pyproject.toml +2 -1
  3. pygui_simple-0.6.0/src/pygui_simple/tkwin/buttonctrl.py +48 -0
  4. pygui_simple-0.5.2/src/pygui_simple/tkcalendar.py → pygui_simple-0.6.0/src/pygui_simple/tkwin/calendarctrl.py +83 -179
  5. pygui_simple-0.6.0/src/pygui_simple/tkwin/canvasctrl.py +176 -0
  6. pygui_simple-0.6.0/src/pygui_simple/tkwin/checkbuttonctrl.py +61 -0
  7. pygui_simple-0.6.0/src/pygui_simple/tkwin/comboboxctrl.py +59 -0
  8. pygui_simple-0.6.0/src/pygui_simple/tkwin/dialogctrl.py +206 -0
  9. pygui_simple-0.6.0/src/pygui_simple/tkwin/entryctrl.py +44 -0
  10. pygui_simple-0.6.0/src/pygui_simple/tkwin/framectrl.py +54 -0
  11. pygui_simple-0.6.0/src/pygui_simple/tkwin/imagebuttonctrl.py +81 -0
  12. pygui_simple-0.6.0/src/pygui_simple/tkwin/imagepanelctrl.py +50 -0
  13. pygui_simple-0.6.0/src/pygui_simple/tkwin/labelctrl.py +53 -0
  14. pygui_simple-0.6.0/src/pygui_simple/tkwin/labelframectrl.py +36 -0
  15. pygui_simple-0.6.0/src/pygui_simple/tkwin/listboxctrl.py +38 -0
  16. pygui_simple-0.5.2/src/pygui_simple/tkmatplot.py → pygui_simple-0.6.0/src/pygui_simple/tkwin/matplotctrl.py +75 -93
  17. pygui_simple-0.6.0/src/pygui_simple/tkwin/menuctrl.py +100 -0
  18. pygui_simple-0.6.0/src/pygui_simple/tkwin/notebookctrl.py +60 -0
  19. pygui_simple-0.6.0/src/pygui_simple/tkwin/picslistviewctrl.py +96 -0
  20. pygui_simple-0.6.0/src/pygui_simple/tkwin/radiobuttonctrl.py +55 -0
  21. pygui_simple-0.6.0/src/pygui_simple/tkwin/radiobuttongroupctrl.py +73 -0
  22. pygui_simple-0.6.0/src/pygui_simple/tkwin/scrollableframectrl.py +214 -0
  23. pygui_simple-0.6.0/src/pygui_simple/tkwin/scrollbarctrl.py +24 -0
  24. pygui_simple-0.6.0/src/pygui_simple/tkwin/scrolledtextctrl.py +36 -0
  25. pygui_simple-0.6.0/src/pygui_simple/tkwin/scrollpickerctrl.py +565 -0
  26. pygui_simple-0.5.2/src/pygui_simple/tkslideswitch.py → pygui_simple-0.6.0/src/pygui_simple/tkwin/slideswitchctrl.py +52 -100
  27. pygui_simple-0.6.0/src/pygui_simple/tkwin/spinboxctrl.py +36 -0
  28. pygui_simple-0.6.0/src/pygui_simple/tkwin/statusbarctrl.py +27 -0
  29. pygui_simple-0.6.0/src/pygui_simple/tkwin/stylectrl.py +27 -0
  30. {pygui_simple-0.5.2/src/pygui_simple → pygui_simple-0.6.0/src/pygui_simple/tkwin}/tkcontrol.py +41 -17
  31. pygui_simple-0.6.0/src/pygui_simple/tkwin/tkcontrols.py +104 -0
  32. pygui_simple-0.6.0/src/pygui_simple/tkwin/tkwin.py +182 -0
  33. pygui_simple-0.6.0/src/pygui_simple/tkwin/tkwm.py +11 -0
  34. pygui_simple-0.6.0/src/pygui_simple/tkwin/toolbarctrl.py +39 -0
  35. pygui_simple-0.6.0/src/pygui_simple/winbasic.py +507 -0
  36. pygui_simple-0.5.2/src/pygui_simple/tkscrollpicker.py +0 -619
  37. pygui_simple-0.5.2/src/pygui_simple/tkwin.py +0 -1488
  38. pygui_simple-0.5.2/src/pygui_simple/winbasic.py +0 -383
  39. {pygui_simple-0.5.2 → pygui_simple-0.6.0}/LICENSE +0 -0
  40. {pygui_simple-0.5.2 → pygui_simple-0.6.0}/README.md +0 -0
  41. {pygui_simple-0.5.2 → pygui_simple-0.6.0}/src/pygui_simple/__init__.py +0 -0
  42. {pygui_simple-0.5.2 → pygui_simple-0.6.0}/src/pygui_simple/py.typed +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pygui_simple
3
- Version: 0.5.2
3
+ Version: 0.6.0
4
4
  Summary: A simple gui library
5
5
  Author: Youchee
6
6
  Author-email: Youchee <youchi.xu@live.com>
@@ -9,6 +9,7 @@ License-File: LICENSE
9
9
  Classifier: Programming Language :: Python :: 3
10
10
  Classifier: Operating System :: OS Independent
11
11
  Requires-Dist: matplotlib>=3.10.8
12
+ Requires-Dist: pyutilities-simple>=0.1.1
12
13
  Requires-Python: >=3.13
13
14
  Project-URL: Homepage, https://github.com/YoucheeXu/pygui
14
15
  Project-URL: Issues, https://github.com/YoucheeXu/pygui/issues
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pygui_simple"
3
- version = "0.5.2"
3
+ version = "0.6.0"
4
4
  description = "A simple gui library"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -9,6 +9,7 @@ authors = [
9
9
  requires-python = ">=3.13"
10
10
  dependencies = [
11
11
  "matplotlib>=3.10.8",
12
+ "pyutilities-simple>=0.1.1",
12
13
  ]
13
14
  classifiers = [
14
15
  "Programming Language :: Python :: 3",
@@ -0,0 +1,48 @@
1
+ import tkinter as tk
2
+ import xml.etree.ElementTree as et
3
+ from tkinter import ttk
4
+ from typing import Any, cast
5
+
6
+ from pygui_simple.tkwin.tkcontrol import tkControl
7
+ from pygui_simple.winbasic import (
8
+ Widget,
9
+ WidgetRegistry,
10
+ WinBasic,
11
+ )
12
+
13
+
14
+ class ButtonCtrl(tkControl):
15
+ def __init__(self, parent: Widget, text: str = "Button", **kwargs: Any):
16
+ master = cast(tk.Misc, parent.control)
17
+ tooltip = cast(str, kwargs.pop("tooltip", ""))
18
+
19
+ ctrl = ttk.Button(master, text=text, **kwargs)
20
+ super().__init__(ctrl, tooltip)
21
+
22
+ @WidgetRegistry.register("Button")
23
+ class tkButtonCtrl(ButtonCtrl):
24
+ def __init__(self, parent: Widget, ctrl_cfg: et.Element, owner: WinBasic):
25
+ attr_dict = ctrl_cfg.attrib
26
+ options: dict[str, Any] = {}
27
+ if "options" in attr_dict:
28
+ options = eval(attr_dict["options"])
29
+ text = attr_dict.get("text")
30
+ assert text is not None
31
+
32
+ tooltip = attr_dict.get("tooltip", "")
33
+ super().__init__(parent, text=text, tooltip=tooltip)
34
+ self._owner: WinBasic = owner
35
+ _ = super().configure(command=self._btn_clicked, **options)
36
+
37
+ self._idctrl: str = ""
38
+ if "id" in attr_dict:
39
+ self._idctrl = attr_dict["id"]
40
+ elif text:
41
+ self._idctrl = text.replace(" ", "").replace(".", "_").replace("\n", "_")
42
+ else:
43
+ raise RuntimeError("No id")
44
+
45
+ def _btn_clicked(self):
46
+ btn = cast(ttk.Button, self._tkctrl)
47
+ _ = self._owner.process_message(self._idctrl,
48
+ mousepos=(btn.winfo_rootx(), btn.winfo_rooty()))
@@ -1,15 +1,19 @@
1
1
  #!/usr/bin/python3
2
2
  # -*- coding: UTF-8 -*-
3
3
  from __future__ import annotations
4
+
4
5
  import calendar
5
6
  import datetime
6
- from typing import override, cast
7
7
  import tkinter as tk
8
8
  import tkinter.font as tkFont
9
+ import xml.etree.ElementTree as et
10
+ from collections.abc import Callable
9
11
  from tkinter import ttk
12
+ from typing import cast, override
10
13
 
11
- from pygui_simple.winbasic import Container
12
- from pygui_simple.tkcontrol import tkControl
14
+ from pygui_simple.tkwin.dialogctrl import DialogCtrl
15
+ from pygui_simple.tkwin.tkcontrol import tkControl
16
+ from pygui_simple.winbasic import Widget, WidgetRegistry, WinBasic
13
17
 
14
18
 
15
19
  class CalendarCtrl(tkControl):
@@ -21,7 +25,7 @@ class CalendarCtrl(tkControl):
21
25
 
22
26
  Attributes:
23
27
  _master: Parent tkinter widget container for the control
24
- _owner: Parent Dialog instance for event message processing
28
+ _callback: callback function
25
29
  _date: First day of the currently displayed calendar month
26
30
  _selection: Tuple of (day text, tree item ID, column) for selected date; None if unselected
27
31
  _contain_frame: Main ttk Frame holding all calendar sub-widgets
@@ -34,21 +38,20 @@ class CalendarCtrl(tkControl):
34
38
  _cmb_month: ttk Combobox for month selection
35
39
  _items: List of Treeview item IDs for calendar week rows
36
40
  """
37
- def __init__(self, parent: tk.Misc, owner: Container, idself: str, **kwargs: object):
41
+ def __init__(self, parent: Widget, **kwargs: object):
38
42
  """ Initialize the calendar control widget.
39
43
 
40
44
  Args:
41
45
  parent: Parent tkinter widget to host the calendar
42
- owner: Dialog instance that owns this control and handles events
43
- idself: Unique control ID for event messaging with the owner
44
46
  **kwargs: Optional configuration parameters
45
47
  fwday: First day of the week (0 = Monday, default: 0)
46
48
  """
47
- ctrl = ttk.Frame(parent)
48
- super().__init__(parent, "", idself, ctrl)
49
+ self._master: tk.Misc = cast(tk.Misc, parent.control)
50
+ ctrl = ttk.Frame(self._master)
51
+ super().__init__(ctrl)
49
52
 
50
- self._master: tk.Misc = parent
51
- self._owner: Container = owner
53
+ self._callback: Callable[[datetime.date], None] | None = \
54
+ cast(Callable[[datetime.date], None] | None, kwargs.get("callback", 0))
52
55
 
53
56
  # first day of week, default to Monday)
54
57
  fwday = cast(int, kwargs.get("fwday", 0))
@@ -112,7 +115,7 @@ class CalendarCtrl(tkControl):
112
115
  AttributeError: If attempting to write to read-only 'year'/'month' attributes
113
116
  """
114
117
  if item in ('year', 'month'):
115
- raise AttributeError("attribute '%s' is not writeable" % item)
118
+ raise AttributeError(f"attribute {item} is not writeable")
116
119
  elif item == 'selectbackground':
117
120
  self._canvas['background'] = value
118
121
  elif item == 'selectforeground':
@@ -131,23 +134,28 @@ class CalendarCtrl(tkControl):
131
134
  Value of the requested attribute
132
135
  """
133
136
  if item in ('year', 'month'):
134
- return getattr(self._date, item)
137
+ return cast(object, getattr(self._date, item))
135
138
  elif item == 'selectbackground':
136
- return self._canvas['background']
139
+ return cast(object, self._canvas['background'])
137
140
  elif item == 'selectforeground':
138
- return self._canvas.itemcget(self._canvas_text, 'fill')
141
+ return cast(object, self._canvas.itemcget(self._canvas_text, 'fill'))
139
142
  else:
140
- r = ttk.tclobjs_to_py({item: ttk.Frame.__getitem__(self, item)})
141
- return r[item]
143
+ r = ttk.tclobjs_to_py({item: ttk.Frame.__getitem__(cast(ttk.Frame, self.control), item)})
144
+ return cast(object, r[item])
142
145
 
143
146
  def __setup_styles(self):
144
147
  """ Define custom ttk styles for calendar navigation arrow buttons."""
145
148
  style = ttk.Style(self._master)
146
- arrow_layout = lambda dir: (
147
- [('Button.focus', {'children': [('Button.%sarrow' % dir, None)]})]
148
- )
149
- style.layout('L.TButton', arrow_layout('left'))
150
- style.layout('R.TButton', arrow_layout('right'))
149
+ def arrow_layout(dir: str) -> ttk._LayoutSpec: # pyright: ignore[reportPrivateUsage]
150
+ return [
151
+ ('Button.focus', {
152
+ 'children': [
153
+ (f'Button.{dir}arrow', None)
154
+ ]
155
+ })
156
+ ]
157
+ _ = style.layout('L.TButton', arrow_layout('left'))
158
+ _ = style.layout('R.TButton', arrow_layout('right'))
151
159
 
152
160
  def __place_widgets(self):
153
161
  """ Layout and position all UI widgets in the control frame."""
@@ -179,7 +187,7 @@ class CalendarCtrl(tkControl):
179
187
 
180
188
  # Month combobox (1-12)
181
189
  self._cmb_month: ttk.Combobox = ttk.Combobox(title_frame, width=3,
182
- values=['%02d' % month for month in range(1,13)], state='readonly')
190
+ values=[f'{month:02d}' for month in range(1,13)], state='readonly')
183
191
  _ = self._cmb_month.current(datetime.datetime.now().month - 1)
184
192
  self._cmb_month.grid(in_=title_frame, column=3, row=0)
185
193
  _ = self._cmb_month.bind("<<ComboboxSelected>>", self._update)
@@ -259,7 +267,7 @@ class CalendarCtrl(tkControl):
259
267
  # Fill each week row with day numbers (empty string for days outside the month)
260
268
  for indx, item in enumerate(self._items):
261
269
  week = cal[indx] if indx < len(cal) else []
262
- fmt_week = [('%02d' % day) if day else '' for day in week]
270
+ fmt_week = [(f'{day:02d}') if day else '' for day in week]
263
271
  self._calendar.item(item, values=fmt_week)
264
272
 
265
273
  def _show_select(self, text: str, bbox: tuple[int, int, int, int]):
@@ -317,13 +325,17 @@ class CalendarCtrl(tkControl):
317
325
  return
318
326
 
319
327
  # Update selection and trigger event
320
- text = '%02d' % text
328
+ text = f'{text:02d}'
321
329
  self._selection = (text, item, column)
322
330
  self._show_select(text, bbox)
323
331
 
324
332
  year, month = self._date.year, self._date.month
325
333
  date = datetime.date(year, month, int(self._selection[0]))
326
- _ = self._owner.process_message(self._idself, event="select_date", val=date)
334
+ self.on_date_changed(date)
335
+
336
+ def on_date_changed(self, date: datetime.date):
337
+ if self._callback:
338
+ self._callback(date)
327
339
 
328
340
  def _prev_month(self):
329
341
  """ Navigate to the previous month and refresh the calendar."""
@@ -378,14 +390,17 @@ class CalendarCtrl(tkControl):
378
390
  self._build_calendar()
379
391
 
380
392
  # Auto-select today's date if viewing current month
381
- if year == datetime.datetime.now().year and month == datetime.datetime.now().month:
382
- day = datetime.datetime.now().day
393
+ today = datetime.datetime.now().date()
394
+ if year == today.year and month == today.month:
395
+ day = today.day
383
396
  for _item, day_list in enumerate(self._cal.monthdayscalendar(year, month)):
384
397
  if day in day_list:
385
398
  item = 'I00' + str(_item + 2)
386
399
  column = '#' + str(day_list.index(day)+1)
387
- _ = self._master.after(100, lambda :self._clicked(item=item, column=column,
400
+ _ = self._master.after(100,
401
+ lambda item=item, column=column: self._clicked(item=item, column=column,
388
402
  widget=self._calendar))
403
+ break
389
404
 
390
405
  def get_date(self):
391
406
  """ Get the currently selected date as a datetime object.
@@ -418,18 +433,14 @@ class CalendarCtrl(tkControl):
418
433
  Returns:
419
434
  bool: True if input is valid, False otherwise
420
435
  """
421
- if content.isdigit() or content == "":
422
- return True
423
- else:
424
- return False
436
+ return (content.isdigit() or content == "")
425
437
 
426
438
  def cancel_select(self):
427
439
  """ Clear the current date selection and hide the highlight."""
428
440
  self._selection = None
429
441
  self._canvas.place_forget()
430
442
 
431
-
432
- class CalendarDialog(Container):
443
+ class CalendarDialog(DialogCtrl):
433
444
  """ A modal, borderless pop-up dialog for date selection.
434
445
 
435
446
  This class creates a top-level tkinter window containing a CalendarCtrl widget
@@ -441,7 +452,7 @@ class CalendarDialog(Container):
441
452
  _calendar_ctrl: Embedded CalendarCtrl widget for date selection
442
453
  _hh: Stored height of the dialog window
443
454
  """
444
- def __init__(self, point: tuple[int, int] | None = None):
455
+ def __init__(self, parent: WinBasic, point: tuple[int, int] | None = None):
445
456
  """ Initialize and render the date selection dialog.
446
457
 
447
458
  Creates a borderless, topmost modal dialog with a calendar control and
@@ -452,87 +463,18 @@ class CalendarDialog(Container):
452
463
  point: Optional (x, y) screen coordinates for the dialog window;
453
464
  defaults to screen center if None
454
465
  """
455
- super().__init__()
456
-
457
466
  # Initialize hidden top-level window
458
- self._top: tk.Toplevel = tk.Toplevel()
459
- self._top.withdraw()
467
+ super().__init__(parent, "", 220, 250)
460
468
 
461
- # Main container frame
462
- frame = ttk.Frame(self._top)
469
+ self.do_show(parent, point)
463
470
 
471
+ @override
472
+ def _construct_children(self):
464
473
  # Embed calendar control and set layout
465
- self._calendar_ctrl: CalendarCtrl = CalendarCtrl(frame, self, "")
466
- self._calendar_ctrl.control.pack(expand = 1, fill = 'both')
467
-
468
- # Bottom action bar with confirm/cancel buttons
469
- bottom_frame = ttk.Frame(frame)
470
- bottom_frame.pack(in_=frame, side='bottom', pady=5)
471
-
472
- # Confirm button (save selection and close)
473
- ttk.Button(bottom_frame, text="确 定", width=6,
474
- command=lambda: self._exit(True)).grid(row=0, column=0, sticky='ns', padx=20)
475
- ttk.Button(bottom_frame, text="取 消", width=6, command=self._exit). \
476
- grid(row=0, column=1, sticky='ne', padx=20)
477
-
478
- # tk.Frame(frame, bg='#565656').\
479
- # place(x=0, y=0, relx=0, rely=0, relwidth=1, relheigh=2/200)
480
- # tk.Frame(frame, bg='#565656'). \
481
- # place(x=0, y=0, relx=0, rely=198/200, relwidth=1, relheigh=2/200)
482
- # tk.Frame(frame, bg='#565656'). \
483
- # place(x=0, y=0, relx=0, rely=0, relwidth=2/200, relheigh=1)
484
- # tk.Frame(frame, bg='#565656'). \
485
- # place(x=0, y=0, relx=198/200, rely=0, relwidth=2/200, relheigh=1)
486
-
487
- # Layout main frame
488
- frame.pack(expand = 1, fill = 'both')
489
-
490
- # Remove window title bar/borders
491
- self._top.overrideredirect(True)
492
- self._top.update_idletasks()
493
-
494
- # Calculate window dimensions and position
495
- width, height = self._top.winfo_reqwidth(), self._top.winfo_reqheight()
496
- self._hh: int = height
497
- # Set position: custom point or screen center
498
- if point:
499
- x, y = point[0], point[1]
500
- else:
501
- x, y = (self._top.winfo_screenwidth() - width)/2, \
502
- (self._top.winfo_screenheight() - height)/2
503
-
504
- # Apply window geometry (size + position)
505
- self._top.geometry(f"{width}x{height}+{x}+{y}")
506
- # _ = self._master.after(300, self._main_judge)
507
-
508
- # Disable window resizing
509
- _ = self._top.resizable(width=tk.FALSE, height=tk.FALSE)
510
- # self._top.transient(self._parent)
511
- # Bind window close event
512
- self._top.protocol("WM_DELETE_WINDOW", self.destroy)
513
-
514
- # Configure modal behavior: topmost, grab focus, block input
515
- self._top.attributes('-topmost', True)
516
- self._top.grab_set() # ensure all input goes to our window
517
- # Show window and wait for user interaction
518
- self._top.deiconify()
519
- self._top.focus_set()
520
- self._top.wait_window()
521
-
522
- def _main_judge(self):
523
- """ Check if the dialog window retains focus; close if focus is lost.
524
-
525
- Recursively monitors window focus state and closes the dialog if it loses
526
- focus to another window/element. Includes exception handling for stability.
527
- """
528
- try:
529
- if self._top.focus_displayof() is None \
530
- or 'toplevel' not in str(self._top.focus_displayof()):
531
- self._exit()
532
- else:
533
- _ = self._top.after(10, self._main_judge)
534
- except:
535
- _ = self._top.after(10, self._main_judge)
474
+ self._calendar_ctrl: CalendarCtrl = CalendarCtrl(self._main_frame)
475
+ cast(tk.Widget, self._calendar_ctrl.control).pack(expand = 1, fill = 'both')
476
+
477
+ return super()._construct_children()
536
478
 
537
479
  def get_datestr(self):
538
480
  """ Retrieve the currently selected date as an ISO-format string.
@@ -543,74 +485,36 @@ class CalendarDialog(Container):
543
485
  """
544
486
  return self._calendar_ctrl.get_datestr()
545
487
 
546
- def _exit(self, confirm: bool = False):
547
- """ Close the dialog and release modal input control.
548
-
549
- Cancels the date selection if closing via cancel/close; preserves the
550
- selection if confirmed. Releases window grab and destroys the dialog.
551
-
552
- Args:
553
- confirm: If True, keep the selected date; if False, clear selection
554
- """
555
- if not confirm:
556
- self._calendar_ctrl.cancel_select()
557
- # Release modal focus and close window
558
- self._top.grab_release()
559
- self._top.destroy()
560
-
561
488
  @override
562
- def destroy(self, **kwargs: object):
563
- """ Override base Dialog destroy method with empty implementation.
564
-
565
- Prevents default destruction logic from interfering with custom
566
- dialog closing behavior defined in _exit().
567
- """
489
+ def _beforego(self, **kwargs: object):
568
490
  pass
569
491
 
492
+ @override
493
+ def _confirm(self, **kwargs: object):
494
+ self.destroy(confirm=True, **kwargs)
570
495
 
571
- if __name__ == "__main__":
572
- class CalendarCtrl_test():
573
- def __init__(self):
574
-
575
- self.root: tk.Tk = tk.Tk()
576
-
577
- # 设置tk窗口在屏幕中心显示
578
- sw = self.root.winfo_screenwidth() # 得到屏幕宽度
579
- sh = self.root.winfo_screenheight() # 得到屏幕高度
580
- ww = 200 # 设置窗口 宽度
581
- wh = 60 # 设置窗口 高度
582
-
583
- x = (sw - ww) / 2
584
- y = (sh - wh) / 2
585
- self.root.geometry("%dx%d+%d+%d" % (ww, wh, x, y))
586
-
587
- self.Frame_row1: tk.Frame = tk.Frame(self.root)
588
- self.Frame_row1.pack()
589
-
590
- self.var_test: tk.StringVar = tk.StringVar()
591
- self.Entry_test: tk.Entry = tk.Entry(self.Frame_row1, width=10,
592
- textvariable=self.var_test, font="宋体, 12",
593
- justify='center', )
594
- self.Entry_test.grid(row=0, column=0, padx=5, pady=5)
595
-
596
- self.Button_test: tk.Button = tk.Button(self.Frame_row1, width=2,
597
- text='*', font="宋体, 12",
598
- justify='center',
599
- command=lambda: self.get_date(self.Entry_test.winfo_rootx(),
600
- self.Entry_test.winfo_rooty() + 20))
601
- self.Button_test.grid(row=0, column=1, padx=5, pady=5)
602
-
603
- self.root.mainloop()
604
-
605
- def get_date(self, x: int, y: int): # x, y位Entry的坐标位置
606
- # 接收弹窗的数据
607
- res = self.ask_date(x, y)
608
- if res is None:
609
- return
610
- self.var_test.set(res)
611
-
612
- def ask_date(self, x: int, y: int):
613
- calendar = CalendarDialog((x, y))
614
- return calendar.get_datestr()
496
+ @override
497
+ def _cancel(self, **kwargs: object):
498
+ self._calendar_ctrl.cancel_select()
499
+ self.destroy(confirm=False, **kwargs)
500
+
501
+ @WidgetRegistry.register("Calendar")
502
+ class tkCalendarCtrl(CalendarCtrl):
503
+ def __init__(self, parent: Widget, ctrl_cfg: et.Element, owner: WinBasic):
504
+ attr_dict = ctrl_cfg.attrib
505
+ options: dict[str, object] = {}
506
+ if "options" in attr_dict:
507
+ options = cast(dict[str, object], eval(attr_dict["options"]))
508
+
509
+ super().__init__(parent, **options)
510
+
511
+ self._owner: WinBasic = owner
512
+ if "id" in attr_dict:
513
+ self._idctrl: str = attr_dict["id"]
514
+ else:
515
+ raise RuntimeError("No id")
615
516
 
616
- app = CalendarCtrl_test()
517
+ @override
518
+ def on_date_changed(self, date: datetime.date):
519
+ _ = self._owner.process_message(self._idctrl, event="select_date", val=date)
520
+ return super().on_date_changed(date)
@@ -0,0 +1,176 @@
1
+ import os
2
+ import tkinter as tk
3
+ import xml.etree.ElementTree as et
4
+ from typing import Any, Literal, cast
5
+
6
+ from PIL import Image, ImageTk
7
+
8
+ from pygui_simple.tkwin.tkcontrol import tkControl
9
+ from pygui_simple.winbasic import (
10
+ Widget,
11
+ WidgetRegistry,
12
+ WinBasic,
13
+ )
14
+
15
+ _FontDescription = str | tuple[str, int] | tuple[str, int, str]
16
+
17
+ @WidgetRegistry.register("Canvas")
18
+ class CanvasCtrl(tkControl):
19
+ def __init__(self, parent: Widget, ctrl_cfg: et.Element, owner: WinBasic):
20
+ master = cast(tk.Misc, parent.control)
21
+ attr_dict = ctrl_cfg.attrib
22
+ options: dict[str, Any] = {}
23
+ if "options" in attr_dict:
24
+ options = eval(attr_dict["options"])
25
+
26
+ self._app_path: str = owner.path
27
+ self._img_cache: list[ImageTk.PhotoImage | None] = []
28
+
29
+ ctrl = tk.Canvas(master, **options)
30
+ super().__init__(ctrl)
31
+
32
+ def create_text(
33
+ self,
34
+ x: float,
35
+ y: float,
36
+ /,
37
+ *,
38
+ activefill: str = "",
39
+ activestipple: str = "",
40
+ anchor: Literal['nw', 'n', 'ne', 'w', 'center', 'e', 'sw', 's', 'se'] = "center",
41
+ angle: float | str = 0,
42
+ disabledfill: str = "",
43
+ disabledstipple: str = "",
44
+ fill: str = "black",
45
+ font: _FontDescription = "",
46
+ justify: Literal['left', 'center', 'right'] = "center",
47
+ offset: float | str = "n",
48
+ state: Literal['normal', 'hidden', 'disabled'] = "normal",
49
+ stipple: str = "",
50
+ tags: str | list[str] | tuple[str, ...] = "",
51
+ text: float | str = "",
52
+ width: float | str = 0
53
+ ) -> int:
54
+ """ Typed wrapper for tk.Canvas.create_text with positional-only x/y and keyword-only remaining args.
55
+
56
+ Args:
57
+ x: Horizontal coordinate for text anchor point, positional-only parameter.
58
+ y: Vertical coordinate for text anchor point, positional-only parameter.
59
+ activefill: Fill color when item is in active state.
60
+ activestipple: Stipple pattern for active fill color.
61
+ anchor: Anchor position aligning text to (x,y) coordinate.
62
+ angle: Rotation angle of text; None uses Tk internal default.
63
+ disabledfill: Fill color when item is disabled.
64
+ disabledstipple: Stipple pattern for disabled fill color.
65
+ fill: Normal text foreground color, default set to black for visibility.
66
+ font: Tk font definition (string or font tuple format), None uses default system font.
67
+ justify: Multi-line text alignment mode.
68
+ offset: Text drawing offset value, None uses default.
69
+ state: Display state of text item(normal/hidden/disabled).
70
+ stipple: Stipple pattern applied to text fill.
71
+ tags: Tag label or tag list bound to this canvas item.
72
+ text: Content string or numeric value to render as text.
73
+ width: Max wrap width for multi-line text, None disables auto line wrap.
74
+
75
+ Returns:
76
+ int: Unique integer canvas item ID returned by native Tk canvas.
77
+ """
78
+ canvas = cast(tk.Canvas, self._tkctrl)
79
+ item_id = canvas.create_text(
80
+ x, y,
81
+ activefill=activefill,
82
+ activestipple=activestipple,
83
+ anchor=anchor,
84
+ angle=angle,
85
+ disabledfill=disabledfill,
86
+ disabledstipple=disabledstipple,
87
+ fill=fill,
88
+ font=font,
89
+ justify=justify,
90
+ offset=offset,
91
+ state=state,
92
+ stipple=stipple,
93
+ tags=tags,
94
+ text=text,
95
+ width=width
96
+ )
97
+ return item_id
98
+
99
+ def create_rectangle(self,
100
+ x1: float,
101
+ y1: float,
102
+ x2: float,
103
+ y2: float,
104
+ /,
105
+ *,
106
+ fill: str = "",
107
+ outline: str = "",
108
+ width: float | str = 1,
109
+ dash: str | int | list[int] | tuple[int, ...] = None,
110
+ stipple: str = "",
111
+ activefill: str = "",
112
+ activeoutline: str = "",
113
+ activedash: str | int | list[int] | tuple[int, ...] = None,
114
+ disabledfill: str = "",
115
+ disabledoutline: str = "",
116
+ state: Literal['normal', 'hidden', 'disabled'] = "normal",
117
+ tags: str | list[str] | tuple[str, ...] = ""
118
+ ) -> int:
119
+ canvas = cast(tk.Canvas, self._tkctrl)
120
+ item_id = canvas.create_rectangle(
121
+ x1, y1, x2, y2,
122
+ fill=fill,
123
+ outline=outline,
124
+ width=width,
125
+ dash=dash,
126
+ stipple=stipple,
127
+ activefill=activefill,
128
+ activeoutline=activeoutline,
129
+ activedash=activedash,
130
+ disabledfill=disabledfill,
131
+ disabledoutline=disabledoutline,
132
+ state=state,
133
+ tags=tags
134
+ )
135
+ return item_id
136
+
137
+ def create_image(
138
+ self,
139
+ x: float,
140
+ y: float,
141
+ /,
142
+ *,
143
+ file_path: str,
144
+ target_w: int,
145
+ target_h: int,
146
+ anchor: Literal['nw', 'n', 'ne', 'w', 'center', 'e', 'sw', 's', 'se'] = "center",
147
+ fallback_fill: str = "#cccccc",
148
+ tags: str | list[str] | tuple[str, ...] | None = None
149
+ ) -> int:
150
+ """Load local image file, auto resize then draw on canvas; auto fallback to colored rectangle on load failure.
151
+ All loaded PhotoImage cached inside instance list to avoid Python GC destroy image resource.
152
+
153
+ Args:
154
+ x: Anchor X coordinate for image placement, positional-only param.
155
+ y: Anchor Y coordinate for image placement, positional-only param.
156
+ file_path: Relative/absolute local path of target image file(png/jpg supported).
157
+ target_w: Fixed pixel width to resize source image.
158
+ target_h: Fixed pixel height to resize source image.
159
+ anchor: Align rule of image against input (x,y) coordinate.
160
+ fallback_fill: Fill color for substitute rectangle when image file missing/corrupted.
161
+ tags: Tag labels bind to generated canvas image item.
162
+
163
+ Returns:
164
+ int: Canvas item ID of either loaded image or fallback substitute rectangle.
165
+ """
166
+ canvas = cast(tk.Canvas, self._tkctrl)
167
+ # Open source image and convert to RGBA to support transparent alpha channel
168
+ image_path = os.path.join(self._app_path, file_path)
169
+ raw_img = Image.open(image_path).convert("RGBA")
170
+ # High quality down/up scale via LANCZOS resample algorithm
171
+ resized_img = raw_img.resize((target_w, target_h), Image.Resampling.LANCZOS)
172
+ photo_obj = ImageTk.PhotoImage(resized_img)
173
+ # Persist image reference into internal cache to prevent garbage collection
174
+ self._img_cache.append(photo_obj)
175
+ item_id = canvas.create_image(x, y, image=photo_obj, anchor=anchor, tags=tags)
176
+ return item_id