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.
- pygui_simple/__init__.py +0 -0
- pygui_simple/cv2_utilities.py +162 -0
- pygui_simple/py.typed +0 -0
- pygui_simple/tkcalendar.py +616 -0
- pygui_simple/tkcontrol.py +112 -0
- pygui_simple/tkmatplot.py +294 -0
- pygui_simple/tkscrollpicker.py +617 -0
- pygui_simple/tkslideswitch.py +448 -0
- pygui_simple/tkwin.py +1344 -0
- pygui_simple/winbasic.py +327 -0
- pygui_simple-0.1.0.dist-info/METADATA +17 -0
- pygui_simple-0.1.0.dist-info/RECORD +14 -0
- pygui_simple-0.1.0.dist-info/WHEEL +4 -0
- pygui_simple-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,616 @@
|
|
|
1
|
+
#!/usr/bin/python3
|
|
2
|
+
# -*- coding: UTF-8 -*-
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
import calendar
|
|
5
|
+
import datetime
|
|
6
|
+
from typing import override, cast
|
|
7
|
+
import tkinter as tk
|
|
8
|
+
import tkinter.font as tkFont
|
|
9
|
+
from tkinter import ttk
|
|
10
|
+
|
|
11
|
+
from pygui.winbasic import Dialog
|
|
12
|
+
from pygui.tkcontrol import tkControl
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class CalendarCtrl(tkControl):
|
|
16
|
+
""" A tkinter-based interactive calendar control for date selection.
|
|
17
|
+
|
|
18
|
+
This widget implements a monthly calendar UI with date picking, month/year navigation,
|
|
19
|
+
and custom selection styling. It integrates with a parent Dialog component to handle
|
|
20
|
+
date selection events. Built on ttk and tkinter for native GUI rendering.
|
|
21
|
+
|
|
22
|
+
Attributes:
|
|
23
|
+
_master: Parent tkinter widget container for the control
|
|
24
|
+
_owner: Parent Dialog instance for event message processing
|
|
25
|
+
_date: First day of the currently displayed calendar month
|
|
26
|
+
_selection: Tuple of (day text, tree item ID, column) for selected date; None if unselected
|
|
27
|
+
_contain_frame: Main ttk Frame holding all calendar sub-widgets
|
|
28
|
+
_cal: Text/Locale calendar generator for formatting month data
|
|
29
|
+
_canvas: Canvas widget for rendering date selection highlight
|
|
30
|
+
_canvas_text: Text item ID on the selection canvas
|
|
31
|
+
_font: Default font for calendar text rendering
|
|
32
|
+
_calendar: ttk Treeview widget displaying the monthly calendar grid
|
|
33
|
+
_cmb_year: ttk Combobox for year selection
|
|
34
|
+
_cmb_month: ttk Combobox for month selection
|
|
35
|
+
_items: List of Treeview item IDs for calendar week rows
|
|
36
|
+
"""
|
|
37
|
+
def __init__(self, parent: tk.Misc, owner: Dialog, idself: str, **kwargs: object):
|
|
38
|
+
""" Initialize the calendar control widget.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
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
|
+
**kwargs: Optional configuration parameters
|
|
45
|
+
fwday: First day of the week (0 = Monday, default: 0)
|
|
46
|
+
"""
|
|
47
|
+
ctrl = ttk.Frame(parent)
|
|
48
|
+
super().__init__(parent, "", idself, ctrl)
|
|
49
|
+
|
|
50
|
+
self._master: tk.Misc = parent
|
|
51
|
+
self._owner: Dialog = owner
|
|
52
|
+
|
|
53
|
+
# first day of week, default to Monday)
|
|
54
|
+
fwday = cast(int, kwargs.get("fwday", 0))
|
|
55
|
+
locale = None
|
|
56
|
+
|
|
57
|
+
# Initialize with current year/month (first day of the month)
|
|
58
|
+
year = datetime.datetime.now().year
|
|
59
|
+
month = datetime.datetime.now().month
|
|
60
|
+
self._date: datetime.date = datetime.datetime(year, month, 1)
|
|
61
|
+
|
|
62
|
+
# No date selected by default
|
|
63
|
+
self._selection: tuple[str, str, str] | None = None
|
|
64
|
+
|
|
65
|
+
self._contain_frame: ttk.Frame = ctrl
|
|
66
|
+
self._cal: calendar.TextCalendar | calendar.LocaleTextCalendar = \
|
|
67
|
+
self.__get_calendar(locale, fwday)
|
|
68
|
+
|
|
69
|
+
# Initialize UI components
|
|
70
|
+
self.__setup_styles() # Create custom ttk widget styles
|
|
71
|
+
self.__place_widgets() # Layout all sub-widgets
|
|
72
|
+
self.__config_calendar() # Configure calendar columns and headers
|
|
73
|
+
self._canvas_text: int = 0
|
|
74
|
+
self._font: tkFont.Font = tkFont.Font()
|
|
75
|
+
|
|
76
|
+
# Selection style colors
|
|
77
|
+
sel_bg = '#ecffc4'
|
|
78
|
+
sel_fg = '#05640e'
|
|
79
|
+
self._canvas: tk.Canvas = self.__setup_selection(sel_bg, sel_fg)
|
|
80
|
+
|
|
81
|
+
# Create 6 empty rows for calendar weeks
|
|
82
|
+
self._items: list[str] = [self._calendar.insert('', 'end', values=[]) for _ in range(6)]
|
|
83
|
+
# Populate and render the calendar
|
|
84
|
+
self._update()
|
|
85
|
+
print(f"first day of week: {self._cal.firstweekday}")
|
|
86
|
+
|
|
87
|
+
def __get_calendar(self, locale: tuple[str | None, str | None] | None = None,
|
|
88
|
+
fwday: int = 0):
|
|
89
|
+
""" Create and return a configured calendar formatter.
|
|
90
|
+
|
|
91
|
+
Args:
|
|
92
|
+
locale: Locale tuple for localized calendar; None for default text calendar
|
|
93
|
+
fwday: First day of the week (0 = Monday)
|
|
94
|
+
|
|
95
|
+
Returns:
|
|
96
|
+
TextCalendar or LocaleTextCalendar: Configured calendar formatting instance
|
|
97
|
+
"""
|
|
98
|
+
if locale is None:
|
|
99
|
+
return calendar.TextCalendar(fwday)
|
|
100
|
+
else:
|
|
101
|
+
return calendar.LocaleTextCalendar(fwday, locale)
|
|
102
|
+
|
|
103
|
+
@override
|
|
104
|
+
def __setitem__(self, item: str, value: object):
|
|
105
|
+
""" Override item assignment for widget attributes.
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
item: Attribute name to modify
|
|
109
|
+
value: New value for the attribute
|
|
110
|
+
|
|
111
|
+
Raises:
|
|
112
|
+
AttributeError: If attempting to write to read-only 'year'/'month' attributes
|
|
113
|
+
"""
|
|
114
|
+
if item in ('year', 'month'):
|
|
115
|
+
raise AttributeError("attribute '%s' is not writeable" % item)
|
|
116
|
+
elif item == 'selectbackground':
|
|
117
|
+
self._canvas['background'] = value
|
|
118
|
+
elif item == 'selectforeground':
|
|
119
|
+
_ = self._canvas.itemconfigure(self._canvas_text, item=value)
|
|
120
|
+
else:
|
|
121
|
+
self._contain_frame.__setitem__(item, value)
|
|
122
|
+
|
|
123
|
+
@override
|
|
124
|
+
def __getitem__(self, item: str):
|
|
125
|
+
""" Override item access for widget attributes.
|
|
126
|
+
|
|
127
|
+
Args:
|
|
128
|
+
item: Attribute name to retrieve
|
|
129
|
+
|
|
130
|
+
Returns:
|
|
131
|
+
Value of the requested attribute
|
|
132
|
+
"""
|
|
133
|
+
if item in ('year', 'month'):
|
|
134
|
+
return getattr(self._date, item)
|
|
135
|
+
elif item == 'selectbackground':
|
|
136
|
+
return self._canvas['background']
|
|
137
|
+
elif item == 'selectforeground':
|
|
138
|
+
return self._canvas.itemcget(self._canvas_text, 'fill')
|
|
139
|
+
else:
|
|
140
|
+
r = ttk.tclobjs_to_py({item: ttk.Frame.__getitem__(self, item)})
|
|
141
|
+
return r[item]
|
|
142
|
+
|
|
143
|
+
def __setup_styles(self):
|
|
144
|
+
""" Define custom ttk styles for calendar navigation arrow buttons."""
|
|
145
|
+
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'))
|
|
151
|
+
|
|
152
|
+
def __place_widgets(self):
|
|
153
|
+
""" Layout and position all UI widgets in the control frame."""
|
|
154
|
+
# Register input validation callback for year combobox
|
|
155
|
+
input_judgment_num = self._master.register(self.input_judgment)
|
|
156
|
+
|
|
157
|
+
# Header frame (navigation + year/month selectors)
|
|
158
|
+
title_frame = ttk.Frame(self._contain_frame)
|
|
159
|
+
gframe = ttk.Frame(self._contain_frame)
|
|
160
|
+
title_frame.pack(in_=self._contain_frame, side='top', pady=5, anchor='center')
|
|
161
|
+
gframe.pack(in_=self._contain_frame, fill=tk.X, pady=5)
|
|
162
|
+
|
|
163
|
+
# Previous/Next month buttons
|
|
164
|
+
lbtn = ttk.Button(title_frame, style='L.TButton', command=self._prev_month)
|
|
165
|
+
lbtn.grid(in_=title_frame, column=0, row=0, padx=12)
|
|
166
|
+
rbtn = ttk.Button(title_frame, style='R.TButton', command=self._next_month)
|
|
167
|
+
rbtn.grid(in_=title_frame, column=5, row=0, padx=12)
|
|
168
|
+
|
|
169
|
+
# Year combobox (last 10 years)
|
|
170
|
+
self._cmb_year: ttk.Combobox = ttk.Combobox(title_frame, width=5,
|
|
171
|
+
values=[str(year) for year in range(datetime.datetime.now().year,
|
|
172
|
+
datetime.datetime.now().year-11, -1)],
|
|
173
|
+
validate='key', validatecommand=(input_judgment_num, '%P'))
|
|
174
|
+
_ = self._cmb_year.current(0)
|
|
175
|
+
self._cmb_year.grid(in_=title_frame, column=1, row=0)
|
|
176
|
+
_ = self._cmb_year.bind('<KeyPress>', lambda event: self._update(event, True))
|
|
177
|
+
_ = self._cmb_year.bind("<<ComboboxSelected>>", self._update)
|
|
178
|
+
tk.Label(title_frame, text = '年', justify = 'left').grid(in_=title_frame, column=2, row=0, padx=(0,5))
|
|
179
|
+
|
|
180
|
+
# Month combobox (1-12)
|
|
181
|
+
self._cmb_month: ttk.Combobox = ttk.Combobox(title_frame, width=3,
|
|
182
|
+
values=['%02d' % month for month in range(1,13)], state='readonly')
|
|
183
|
+
_ = self._cmb_month.current(datetime.datetime.now().month - 1)
|
|
184
|
+
self._cmb_month.grid(in_=title_frame, column=3, row=0)
|
|
185
|
+
_ = self._cmb_month.bind("<<ComboboxSelected>>", self._update)
|
|
186
|
+
tk.Label(title_frame, text='月', justify='left').grid(in_=title_frame, column=4, row=0)
|
|
187
|
+
|
|
188
|
+
# Main calendar grid widget
|
|
189
|
+
self._calendar: ttk.Treeview = ttk.Treeview(gframe, show='', selectmode='none', height=7)
|
|
190
|
+
self._calendar.pack(expand=1, fill='both', side='bottom', padx=5)
|
|
191
|
+
|
|
192
|
+
def _generate_week_cols(self, fwd: int):
|
|
193
|
+
""" Generate ordered weekday column labels (Chinese) based on the first week day.
|
|
194
|
+
|
|
195
|
+
Base order: 一 (Mon) → 日 (Sun); rotated to match the first week day.
|
|
196
|
+
|
|
197
|
+
Args:
|
|
198
|
+
fwd: First day of the week (0-6, 0 = Monday)
|
|
199
|
+
|
|
200
|
+
Returns:
|
|
201
|
+
list[str]: Rotated list of Chinese weekday labels
|
|
202
|
+
|
|
203
|
+
Raises:
|
|
204
|
+
ValueError: If fwd is outside the valid 0-6 range
|
|
205
|
+
"""
|
|
206
|
+
BASE_WEEK = ['一','二','三','四','五','六','日']
|
|
207
|
+
|
|
208
|
+
# Validate input (only accept valid Chinese weekdays)
|
|
209
|
+
if fwd < 0 or fwd > 6:
|
|
210
|
+
raise ValueError("Invalid first day! Must be: 0~6")
|
|
211
|
+
|
|
212
|
+
# Rotate the list: put first day at index 0
|
|
213
|
+
cols = BASE_WEEK[fwd:] + BASE_WEEK[:fwd]
|
|
214
|
+
return cols
|
|
215
|
+
|
|
216
|
+
def __config_calendar(self):
|
|
217
|
+
""" Configure the calendar Treeview: columns, headers, and column widths."""
|
|
218
|
+
cols = self._generate_week_cols(self._cal.firstweekday)
|
|
219
|
+
self._calendar['columns'] = cols
|
|
220
|
+
_ = self._calendar.tag_configure('header', background='grey90')
|
|
221
|
+
_ = self._calendar.insert('', 'end', values=cols, tags='header')
|
|
222
|
+
|
|
223
|
+
# Set uniform column width based on the longest weekday label
|
|
224
|
+
font = tkFont.Font()
|
|
225
|
+
maxwidth = max(font.measure(col) for col in cols)
|
|
226
|
+
for col in cols:
|
|
227
|
+
_ = self._calendar.column(col, width=maxwidth, minwidth=maxwidth,
|
|
228
|
+
anchor='center')
|
|
229
|
+
|
|
230
|
+
def __setup_selection(self, sel_bg: str, sel_fg: str):
|
|
231
|
+
""" Initialize the selection canvas and click event bindings.
|
|
232
|
+
|
|
233
|
+
Args:
|
|
234
|
+
sel_bg: Background color for selected date highlight
|
|
235
|
+
sel_fg: Text color for selected date
|
|
236
|
+
|
|
237
|
+
Returns:
|
|
238
|
+
tk.Canvas: Configured selection canvas widget
|
|
239
|
+
"""
|
|
240
|
+
def __canvas_forget(_: tk.Event[tk.Canvas] | tk.Event[ttk.Treeview]):
|
|
241
|
+
canvas.place_forget()
|
|
242
|
+
self._selection = None
|
|
243
|
+
|
|
244
|
+
canvas = tk.Canvas(self._calendar, background=sel_bg,
|
|
245
|
+
borderwidth=0, highlightthickness=0)
|
|
246
|
+
self._canvas_text = canvas.create_text(0, 0, fill=sel_fg, anchor='w')
|
|
247
|
+
|
|
248
|
+
# Bind events to clear selection
|
|
249
|
+
_ = canvas.bind('<Button-1>', __canvas_forget)
|
|
250
|
+
_ = self._calendar.bind('<Configure>', __canvas_forget)
|
|
251
|
+
_ = self._calendar.bind('<Button-1>', self._clicked)
|
|
252
|
+
return canvas
|
|
253
|
+
|
|
254
|
+
def _build_calendar(self):
|
|
255
|
+
""" Populate the Treeview with day values for the current month/year."""
|
|
256
|
+
year, month = self._date.year, self._date.month
|
|
257
|
+
cal = self._cal.monthdayscalendar(year, month)
|
|
258
|
+
|
|
259
|
+
# Fill each week row with day numbers (empty string for days outside the month)
|
|
260
|
+
for indx, item in enumerate(self._items):
|
|
261
|
+
week = cal[indx] if indx < len(cal) else []
|
|
262
|
+
fmt_week = [('%02d' % day) if day else '' for day in week]
|
|
263
|
+
self._calendar.item(item, values=fmt_week)
|
|
264
|
+
|
|
265
|
+
def _show_select(self, text: str, bbox: tuple[int, int, int, int]):
|
|
266
|
+
""" Render the date selection highlight on the calendar grid.
|
|
267
|
+
|
|
268
|
+
Args:
|
|
269
|
+
text: Day number to display in the selection
|
|
270
|
+
bbox: Bounding box (x, y, width, height) for the selection area
|
|
271
|
+
"""
|
|
272
|
+
x, y, width, height = bbox
|
|
273
|
+
textw = self._font.measure(text)
|
|
274
|
+
canvas = self._canvas
|
|
275
|
+
|
|
276
|
+
# Resize canvas and center text
|
|
277
|
+
_ = canvas.configure(width=width, height=height)
|
|
278
|
+
canvas.coords(self._canvas_text, (width - textw)/2, height / 2 - 1)
|
|
279
|
+
_ = canvas.itemconfigure(self._canvas_text, text=text)
|
|
280
|
+
canvas.place(in_=self._calendar, x=x, y=y)
|
|
281
|
+
|
|
282
|
+
def _clicked(self, evt: tk.Event[ttk.Treeview] | None = None,
|
|
283
|
+
item: str | None = None, column: str | None = None, widget: ttk.Treeview | None = None):
|
|
284
|
+
""" Handle mouse click events to select a date on the calendar.
|
|
285
|
+
|
|
286
|
+
Triggers selection highlight and sends a 'select_date' event to the owner dialog.
|
|
287
|
+
|
|
288
|
+
Args:
|
|
289
|
+
evt: Tkinter click event; None for programmatic calls
|
|
290
|
+
item: Treeview row ID (optional, for programmatic selection)
|
|
291
|
+
column: Treeview column ID (optional, for programmatic selection)
|
|
292
|
+
widget: Target Treeview widget (optional)
|
|
293
|
+
"""
|
|
294
|
+
# Resolve click target from event if not provided
|
|
295
|
+
if evt and not item:
|
|
296
|
+
x, y, widget = evt.x, evt.y, evt.widget
|
|
297
|
+
item = widget.identify_row(y)
|
|
298
|
+
column = widget.identify_column(x)
|
|
299
|
+
|
|
300
|
+
# Ignore clicks on non-day areas
|
|
301
|
+
if not column or item not in self._items:
|
|
302
|
+
return
|
|
303
|
+
assert(widget is not None)
|
|
304
|
+
|
|
305
|
+
item_values = widget.item(item)['values']
|
|
306
|
+
if not len(item_values):
|
|
307
|
+
return
|
|
308
|
+
|
|
309
|
+
text = item_values[int(column[1]) - 1]
|
|
310
|
+
if not text:
|
|
311
|
+
return
|
|
312
|
+
|
|
313
|
+
# Delay selection if calendar is not yet rendered
|
|
314
|
+
bbox = widget.bbox(item, column)
|
|
315
|
+
if not bbox:
|
|
316
|
+
_ = self._master.after(20, lambda: self._clicked(None, item, column, widget))
|
|
317
|
+
return
|
|
318
|
+
|
|
319
|
+
# Update selection and trigger event
|
|
320
|
+
text = '%02d' % text
|
|
321
|
+
self._selection = (text, item, column)
|
|
322
|
+
self._show_select(text, bbox)
|
|
323
|
+
|
|
324
|
+
year, month = self._date.year, self._date.month
|
|
325
|
+
date = datetime.date(year, month, int(self._selection[0]))
|
|
326
|
+
_ = self._owner.process_message(self._idself, event="select_date", val=date)
|
|
327
|
+
|
|
328
|
+
def _prev_month(self):
|
|
329
|
+
""" Navigate to the previous month and refresh the calendar."""
|
|
330
|
+
self._canvas.place_forget()
|
|
331
|
+
self._selection = None
|
|
332
|
+
|
|
333
|
+
# Calculate first day of the previous month
|
|
334
|
+
self._date = self._date - datetime.timedelta(days=1)
|
|
335
|
+
self._date = datetime.datetime(self._date.year, self._date.month, 1)
|
|
336
|
+
|
|
337
|
+
# Update comboboxes and refresh UI
|
|
338
|
+
self._cmb_year.set(self._date.year)
|
|
339
|
+
self._cmb_month.set(self._date.month)
|
|
340
|
+
self._update()
|
|
341
|
+
|
|
342
|
+
def _next_month(self):
|
|
343
|
+
""" Navigate to the next month and refresh the calendar."""
|
|
344
|
+
self._canvas.place_forget()
|
|
345
|
+
self._selection = None
|
|
346
|
+
|
|
347
|
+
# Calculate first day of the next month
|
|
348
|
+
year, month = self._date.year, self._date.month
|
|
349
|
+
self._date = self._date + datetime.timedelta(
|
|
350
|
+
days=calendar.monthrange(year, month)[1] + 1)
|
|
351
|
+
self._date = datetime.datetime(self._date.year, self._date.month, 1)
|
|
352
|
+
|
|
353
|
+
# Update comboboxes and refresh UI
|
|
354
|
+
self._cmb_year.set(self._date.year)
|
|
355
|
+
self._cmb_month.set(self._date.month)
|
|
356
|
+
self._update()
|
|
357
|
+
|
|
358
|
+
def _update(self, event: tk.Event[ttk.Combobox] | None = None, key: bool = False):
|
|
359
|
+
""" Refresh the calendar UI when year/month selections change.
|
|
360
|
+
|
|
361
|
+
Args:
|
|
362
|
+
event: Tkinter combobox change event (optional)
|
|
363
|
+
key: Flag for key press events; only refresh on Enter key
|
|
364
|
+
"""
|
|
365
|
+
# Skip refresh for non-Enter key presses
|
|
366
|
+
if key and event and event.keysym != 'Return':
|
|
367
|
+
return
|
|
368
|
+
|
|
369
|
+
# Validate year input
|
|
370
|
+
year = int(self._cmb_year.get())
|
|
371
|
+
month = int(self._cmb_month.get())
|
|
372
|
+
if year == 0 or year > 9999:
|
|
373
|
+
return
|
|
374
|
+
|
|
375
|
+
# Reset selection and rebuild calendar
|
|
376
|
+
self._canvas.place_forget()
|
|
377
|
+
self._date = datetime.datetime(year, month, 1)
|
|
378
|
+
self._build_calendar()
|
|
379
|
+
|
|
380
|
+
# 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
|
|
383
|
+
for _item, day_list in enumerate(self._cal.monthdayscalendar(year, month)):
|
|
384
|
+
if day in day_list:
|
|
385
|
+
item = 'I00' + str(_item + 2)
|
|
386
|
+
column = '#' + str(day_list.index(day)+1)
|
|
387
|
+
_ = self._master.after(100, lambda :self._clicked(item=item, column=column,
|
|
388
|
+
widget=self._calendar))
|
|
389
|
+
|
|
390
|
+
def get_date(self):
|
|
391
|
+
""" Get the currently selected date as a datetime object.
|
|
392
|
+
|
|
393
|
+
Returns:
|
|
394
|
+
datetime.date | None: Selected date; None if no selection
|
|
395
|
+
"""
|
|
396
|
+
if not self._selection:
|
|
397
|
+
return None
|
|
398
|
+
year, month = self._date.year, self._date.month
|
|
399
|
+
return datetime.date(year, month, int(self._selection[0]))
|
|
400
|
+
|
|
401
|
+
def get_datestr(self):
|
|
402
|
+
""" Get the currently selected date as an ISO format string.
|
|
403
|
+
|
|
404
|
+
Returns:
|
|
405
|
+
str | None: Date string (YYYY-MM-DD); None if no selection
|
|
406
|
+
"""
|
|
407
|
+
if not self._selection:
|
|
408
|
+
return None
|
|
409
|
+
year, month = self._date.year, self._date.month
|
|
410
|
+
return str(datetime.date(year, month, int(self._selection[0])))
|
|
411
|
+
|
|
412
|
+
def input_judgment(self, content: str):
|
|
413
|
+
""" Validate input for the year combobox (only digits/empty allowed).
|
|
414
|
+
|
|
415
|
+
Args:
|
|
416
|
+
content: Input string from the year combobox
|
|
417
|
+
|
|
418
|
+
Returns:
|
|
419
|
+
bool: True if input is valid, False otherwise
|
|
420
|
+
"""
|
|
421
|
+
if content.isdigit() or content == "":
|
|
422
|
+
return True
|
|
423
|
+
else:
|
|
424
|
+
return False
|
|
425
|
+
|
|
426
|
+
def cancel_select(self):
|
|
427
|
+
""" Clear the current date selection and hide the highlight."""
|
|
428
|
+
self._selection = None
|
|
429
|
+
self._canvas.place_forget()
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
class CalendarDialog(Dialog):
|
|
433
|
+
""" A modal, borderless pop-up dialog for date selection.
|
|
434
|
+
|
|
435
|
+
This class creates a top-level tkinter window containing a CalendarCtrl widget
|
|
436
|
+
and confirm/cancel buttons. It acts as a standalone date picker with modal
|
|
437
|
+
behavior (blocks input to other windows until closed) and custom positioning.
|
|
438
|
+
|
|
439
|
+
Attributes:
|
|
440
|
+
_top: Borderless Toplevel window for the dialog UI
|
|
441
|
+
_calendar_ctrl: Embedded CalendarCtrl widget for date selection
|
|
442
|
+
_hh: Stored height of the dialog window
|
|
443
|
+
"""
|
|
444
|
+
def __init__(self, point: tuple[int, int] | None = None):
|
|
445
|
+
""" Initialize and render the date selection dialog.
|
|
446
|
+
|
|
447
|
+
Creates a borderless, topmost modal dialog with a calendar control and
|
|
448
|
+
action buttons. Positions the window at the given coordinates or center
|
|
449
|
+
of the screen if no position is provided.
|
|
450
|
+
|
|
451
|
+
Args:
|
|
452
|
+
point: Optional (x, y) screen coordinates for the dialog window;
|
|
453
|
+
defaults to screen center if None
|
|
454
|
+
"""
|
|
455
|
+
super().__init__("", 0, 0)
|
|
456
|
+
|
|
457
|
+
# Initialize hidden top-level window
|
|
458
|
+
self._top: tk.Toplevel = tk.Toplevel()
|
|
459
|
+
self._top.withdraw()
|
|
460
|
+
|
|
461
|
+
# Main container frame
|
|
462
|
+
frame = ttk.Frame(self._top)
|
|
463
|
+
|
|
464
|
+
# 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)
|
|
536
|
+
|
|
537
|
+
def get_datestr(self):
|
|
538
|
+
""" Retrieve the currently selected date as an ISO-format string.
|
|
539
|
+
|
|
540
|
+
Returns:
|
|
541
|
+
str | None: Date string (YYYY-MM-DD) if a date is selected,
|
|
542
|
+
None if no selection exists
|
|
543
|
+
"""
|
|
544
|
+
return self._calendar_ctrl.get_datestr()
|
|
545
|
+
|
|
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
|
+
@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
|
+
"""
|
|
568
|
+
pass
|
|
569
|
+
|
|
570
|
+
|
|
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()
|
|
615
|
+
|
|
616
|
+
app = CalendarCtrl_test()
|