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
pygui_simple/tkwin.py
ADDED
|
@@ -0,0 +1,1344 @@
|
|
|
1
|
+
# !/usr/bin/python3
|
|
2
|
+
# -*- coding: UTF-8 -*-
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
import builtins as __builtin__
|
|
5
|
+
# from _typeshed import SupportsWrite
|
|
6
|
+
import sys
|
|
7
|
+
import os
|
|
8
|
+
import platform
|
|
9
|
+
import ctypes
|
|
10
|
+
from functools import partial
|
|
11
|
+
# from collections import OrderedDict
|
|
12
|
+
from typing import Literal, Any, override, cast, Unpack
|
|
13
|
+
from typing import Protocol, TypeVar, Generic
|
|
14
|
+
# from typing import get_args, get_origin
|
|
15
|
+
# from collections.abc import Callable
|
|
16
|
+
|
|
17
|
+
import tkinter as tk
|
|
18
|
+
import tkinter.messagebox as tkMessageBox
|
|
19
|
+
from tkinter import ttk
|
|
20
|
+
from tkinter import scrolledtext
|
|
21
|
+
import xml.etree.ElementTree as et
|
|
22
|
+
from ast import literal_eval
|
|
23
|
+
|
|
24
|
+
import cv2
|
|
25
|
+
# from PIL import Image
|
|
26
|
+
from PIL import ImageTk
|
|
27
|
+
|
|
28
|
+
from idlelib.statusbar import MultiStatusBar
|
|
29
|
+
from idlelib.tooltip import Hovertip
|
|
30
|
+
|
|
31
|
+
from pygui.winbasic import EventHanlder, Widget, Container, Dialog, WinBasic
|
|
32
|
+
from pygui.tkcontrol import tkControl
|
|
33
|
+
from pygui.tkmatplot import MatPlotCtrl
|
|
34
|
+
from pygui.tkslideswitch import SlideSwitchCtrl
|
|
35
|
+
import pygui.cv2_utilities as cv2u
|
|
36
|
+
from pygui.tkcalendar import CalendarCtrl
|
|
37
|
+
from pygui.tkscrollpicker import ScrollPickerCtrl, TimeScrollPickerCtrl
|
|
38
|
+
|
|
39
|
+
IS_WINDOWS = platform.system() == "Windows"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class LabelCtrl(tkControl):
|
|
43
|
+
def __init__(self, parent: tk.Misc, owner: Dialog, idself: str,
|
|
44
|
+
text: str, clickable: bool, **options: Any):
|
|
45
|
+
# po(f"{idself}: {options}")
|
|
46
|
+
ctrl = ttk.Label(parent, text=text, **options)
|
|
47
|
+
super().__init__(parent, text, idself, ctrl)
|
|
48
|
+
if clickable:
|
|
49
|
+
_= ctrl.bind("<Button-1>",
|
|
50
|
+
lambda e: owner.process_message(idself,
|
|
51
|
+
mousepos=e.widget.winfo_pointerxy()))
|
|
52
|
+
|
|
53
|
+
def get_text(self):
|
|
54
|
+
lblctrl = cast(ttk.Label, self._tkctrl)
|
|
55
|
+
return cast(str, lblctrl["text"])
|
|
56
|
+
|
|
57
|
+
def set_text(self, val: str):
|
|
58
|
+
lblctrl = cast(ttk.Label, self._tkctrl)
|
|
59
|
+
lblctrl["text"] = val
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class EntryCtrl(tkControl):
|
|
63
|
+
def __init__(self, parent: tk.Misc, **options: Any):
|
|
64
|
+
ctrl = ttk.Entry(parent)
|
|
65
|
+
super().__init__(parent, "", "", ctrl)
|
|
66
|
+
self._var: tk.StringVar = tk.StringVar()
|
|
67
|
+
_= ctrl.configure(textvariable=self._var, **options)
|
|
68
|
+
|
|
69
|
+
def get_val(self) -> str:
|
|
70
|
+
return self._var.get()
|
|
71
|
+
|
|
72
|
+
def set_val(self, val: str):
|
|
73
|
+
self._var.set(val)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class ImagePanelCtrl(tkControl):
|
|
77
|
+
def __init__(self, parent: tk.Misc, idself: str, imagefile: str, *,
|
|
78
|
+
width: int = 0, height: int = 0, **options: Any):
|
|
79
|
+
ctrl = tk.Label(parent)
|
|
80
|
+
super().__init__(parent, "", idself, ctrl)
|
|
81
|
+
self._image: ImageTk.PhotoImage | None = None
|
|
82
|
+
if imagefile:
|
|
83
|
+
image = self._read_image(imagefile, width, height)
|
|
84
|
+
_ = ctrl.configure(text="", image=image, anchor=tk.CENTER, **options)
|
|
85
|
+
self._image = image
|
|
86
|
+
else:
|
|
87
|
+
_ = ctrl.configure(text="", anchor=tk.CENTER, **options)
|
|
88
|
+
|
|
89
|
+
def _read_image(self, imagepath: str, w: int, h: int):
|
|
90
|
+
image = cv2u.read_image(imagepath)
|
|
91
|
+
if w:
|
|
92
|
+
# pv(w)
|
|
93
|
+
# pv(h)
|
|
94
|
+
image = cv2u.scale_image(image, w, h)
|
|
95
|
+
image2 = cv2u.image2photo(image)
|
|
96
|
+
return image2
|
|
97
|
+
|
|
98
|
+
def display_image(self, image: cv2.typing.MatLike):
|
|
99
|
+
image2 = cv2u.image2photo(image)
|
|
100
|
+
|
|
101
|
+
_ = cast(tk.Label, super().control).configure(image=image2)
|
|
102
|
+
self._image = image2
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class ButtonCtrl(tkControl):
|
|
106
|
+
def __init__(self, parent: tk.Misc, owner: Dialog, idself: str, text: str,
|
|
107
|
+
**options: Any):
|
|
108
|
+
ctrl = ttk.Button(parent, text=text, **options)
|
|
109
|
+
tkControl.__init__(self, parent, text, idself, ctrl)
|
|
110
|
+
self._owner: Dialog = owner
|
|
111
|
+
_ = ctrl.configure(command=self._btn_clicked, **options)
|
|
112
|
+
|
|
113
|
+
def _btn_clicked(self):
|
|
114
|
+
btn = cast(ttk.Button, self._tkctrl)
|
|
115
|
+
_ = self._owner.process_message(self._idself,
|
|
116
|
+
mousepos=(btn.winfo_rootx(), btn.winfo_rooty()))
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class ImageBtttonCtrl(tkControl):
|
|
120
|
+
def __init__(self, parent: tk.Misc, owner: Dialog, idself: str, *,
|
|
121
|
+
respath: str, imagefile: str, text: str | None,
|
|
122
|
+
width: int = 0, height: int = 0,
|
|
123
|
+
**options: Any):
|
|
124
|
+
ctrl = tk.Button(parent, **options)
|
|
125
|
+
title = text if text else ""
|
|
126
|
+
tkControl.__init__(self, parent, title, idself, ctrl)
|
|
127
|
+
self._res_path: str = respath
|
|
128
|
+
self._ww: int = width
|
|
129
|
+
self._image: ImageTk.PhotoImage
|
|
130
|
+
self._hh: int = height if height else width if width else 0
|
|
131
|
+
|
|
132
|
+
imagefile = os.path.join(self._res_path, imagefile)
|
|
133
|
+
eimg = self._read_image(imagefile, self._ww, self._hh)
|
|
134
|
+
# if eimg is None:
|
|
135
|
+
# raise RuntimeError(f"fail to read image: {imagefile}")
|
|
136
|
+
|
|
137
|
+
def cmd():
|
|
138
|
+
_ = owner.process_message(idself,
|
|
139
|
+
mousepos=(ctrl.winfo_rootx(), ctrl.winfo_rooty()))
|
|
140
|
+
|
|
141
|
+
if text is not None:
|
|
142
|
+
_ = ctrl.configure(text=text, image=eimg, command=cmd, compound=tk.LEFT,
|
|
143
|
+
relief=tk.FLAT, **options)
|
|
144
|
+
# **options)
|
|
145
|
+
else:
|
|
146
|
+
_ = ctrl.configure(image=eimg, command=cmd, relief=tk.FLAT, **options)
|
|
147
|
+
self._image = eimg
|
|
148
|
+
|
|
149
|
+
def _read_image(self, imagepath: str, w: int, h: int):
|
|
150
|
+
# image = cv2.imread(imagepath, cv2.IMREAD_UNCHANGED)
|
|
151
|
+
image = cv2u.read_image(imagepath)
|
|
152
|
+
if w:
|
|
153
|
+
# image = cv2.resize(image, (w, h), interpolation=cv2.INTER_CUBIC)
|
|
154
|
+
image = cv2u.scale_image(image, w, h, cv2.INTER_CUBIC)
|
|
155
|
+
image2 = cv2u.image2photo(image)
|
|
156
|
+
return image2
|
|
157
|
+
|
|
158
|
+
# TODO: wait to test
|
|
159
|
+
def change_image(self, imagefile: str, w: int = 0, h: int = 0):
|
|
160
|
+
imagefile = os.path.join(self._res_path, imagefile)
|
|
161
|
+
if not w:
|
|
162
|
+
w, h = self._ww, self._hh
|
|
163
|
+
photo = self._read_image(imagefile, w, h)
|
|
164
|
+
# if photo is not None:
|
|
165
|
+
btn = cast(tk.Button, super().control)
|
|
166
|
+
_ = btn.configure(image=photo)
|
|
167
|
+
# btn.image = photo
|
|
168
|
+
self._image = photo
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class CheckButtonCtrl(tkControl):
|
|
172
|
+
def __init__(self, parent: tk.Misc, owner: Dialog, idself: str, *,
|
|
173
|
+
text: str, vartext: str, select: bool, **options: Any):
|
|
174
|
+
ctrl = tk.Checkbutton(parent)
|
|
175
|
+
tkControl.__init__(self, parent, "", idself, ctrl)
|
|
176
|
+
self._vartext: str = "_" + vartext
|
|
177
|
+
self.__dict__[self._vartext] = tk.IntVar()
|
|
178
|
+
variable = cast(tk.IntVar, self.__dict__[self._vartext])
|
|
179
|
+
_ = ctrl.configure(text=text,
|
|
180
|
+
variable=variable, **options)
|
|
181
|
+
_ = variable.trace_add("write",
|
|
182
|
+
lambda u0, u1, u2: owner.process_message(vartext, event="Changed",
|
|
183
|
+
val=variable.get()))
|
|
184
|
+
|
|
185
|
+
if select:
|
|
186
|
+
ctrl.select()
|
|
187
|
+
|
|
188
|
+
def get_val(self) -> int:
|
|
189
|
+
return cast(tk.IntVar, self.__dict__[self._vartext]).get()
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
class ComboboxCtrl(tkControl):
|
|
193
|
+
def __init__(self, parent: tk.Misc, owner: Dialog, *,
|
|
194
|
+
idself: str, default: int, **options: Any):
|
|
195
|
+
ctrl = ttk.Combobox(parent)
|
|
196
|
+
super().__init__(parent, "", idself, ctrl)
|
|
197
|
+
self._var: tk.StringVar = tk.StringVar()
|
|
198
|
+
_ = ctrl.configure(textvariable=self._var, **options)
|
|
199
|
+
_ = ctrl.current(default)
|
|
200
|
+
_ = ctrl.bind(
|
|
201
|
+
"<<ComboboxSelected>>",
|
|
202
|
+
lambda event: owner.process_message(
|
|
203
|
+
idself, event="Selected", val=self._var.get()
|
|
204
|
+
),
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
def get_val(self) -> str:
|
|
208
|
+
return self._var.get()
|
|
209
|
+
|
|
210
|
+
def set_val(self, val: str):
|
|
211
|
+
self._var.set(val)
|
|
212
|
+
|
|
213
|
+
def select(self, idx: int):
|
|
214
|
+
ctrl = cast(ttk.Combobox, self._tkctrl)
|
|
215
|
+
return ctrl.current(idx)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
class ListboxCtrl(tkControl):
|
|
219
|
+
def __init__(self, parent: tk.Misc, idself: str,
|
|
220
|
+
**options: Any):
|
|
221
|
+
ctrl = tk.Listbox(parent)
|
|
222
|
+
tkControl.__init__(self, parent, "", idself, ctrl)
|
|
223
|
+
|
|
224
|
+
def insert(self, index: str | int, *elements: str | float):
|
|
225
|
+
ctrl = cast(tk.Listbox, self._tkctrl)
|
|
226
|
+
ctrl.insert(index, *elements)
|
|
227
|
+
# self.scroll_to_bottom_if_needed()
|
|
228
|
+
|
|
229
|
+
def scroll_to_bottom_if_needed(self):
|
|
230
|
+
ctrl = cast(tk.Listbox, self._tkctrl)
|
|
231
|
+
# 获取滚动条位置
|
|
232
|
+
scrollbar_position = ctrl.yview()[1]
|
|
233
|
+
# 检查滚动条是否在最底部
|
|
234
|
+
if scrollbar_position != 1.0:
|
|
235
|
+
# 在最底部时,执行自动滚动
|
|
236
|
+
ctrl.see(tk.END)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
class RadioButtonCtrl(tkControl):
|
|
240
|
+
def __init__(self, parent: tk.Misc, owner: Dialog, idself: str, *,
|
|
241
|
+
text: str, vartext: str, value: int, **options: Any):
|
|
242
|
+
ctrl = ttk.Radiobutton(parent)
|
|
243
|
+
tkControl.__init__(self, parent, "", idself, ctrl)
|
|
244
|
+
# self._app: GuiBasic = app
|
|
245
|
+
self._master: Dialog = owner
|
|
246
|
+
self._vartext: str = vartext
|
|
247
|
+
if self._vartext not in self._master.__dict__:
|
|
248
|
+
self._master.__dict__[self._vartext] = tk.IntVar()
|
|
249
|
+
variable = cast(tk.IntVar, self._master.__dict__[self._vartext])
|
|
250
|
+
_ = ctrl.configure(text=text,
|
|
251
|
+
variable=variable, value=value,
|
|
252
|
+
command=lambda: owner.process_message(vartext, event="Changed", val=variable.get()),
|
|
253
|
+
**options)
|
|
254
|
+
|
|
255
|
+
def get_val(self) -> int:
|
|
256
|
+
# return self.__dict__[self._vartext].get()
|
|
257
|
+
return cast(tk.IntVar, self._master.__dict__[self._vartext]).get()
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
class RadioButtonGroupCtrl(tkControl):
|
|
261
|
+
def __init__(self, parent: tk.Misc, app: WinBasic, owner: Dialog, idself: str, *,
|
|
262
|
+
text: str, subctrlcfg: et.Element,
|
|
263
|
+
level: int, **options: Any):
|
|
264
|
+
ctrl = ttk.LabelFrame(parent)
|
|
265
|
+
super().__init__(parent, text, idself, ctrl)
|
|
266
|
+
# self._idself: str = idself
|
|
267
|
+
# self._var_val: tk.IntVar = tk.IntVar()
|
|
268
|
+
self._vartext: str = "_var" + text.replace(" ", "_")
|
|
269
|
+
self._app: WinBasic = app
|
|
270
|
+
self._owner: Dialog = owner
|
|
271
|
+
# pv(options)
|
|
272
|
+
_ = self.configure(text=text, **options)
|
|
273
|
+
# self._radbutton_lst: list[ttk.Radiobutton] = []
|
|
274
|
+
self._radbutton_lst: list[RadioButtonCtrl] = []
|
|
275
|
+
_ = self._create_subctrls(subctrlcfg, level)
|
|
276
|
+
|
|
277
|
+
def get_val(self) -> int:
|
|
278
|
+
# return self._var_val.get()
|
|
279
|
+
return cast(tk.IntVar, self._app.__dict__[self._vartext]).get()
|
|
280
|
+
|
|
281
|
+
def set_val(self, val: int):
|
|
282
|
+
# self._var_val.set(val)
|
|
283
|
+
cast(tk.IntVar, self._app.__dict__[self._vartext]).set(val)
|
|
284
|
+
|
|
285
|
+
def _create_subctrls(self, subctrls: et.Element, level: int):
|
|
286
|
+
for subctrl_cfg in subctrls:
|
|
287
|
+
radbtn_attr_dict = subctrl_cfg.attrib
|
|
288
|
+
value = int(radbtn_attr_dict["value"])
|
|
289
|
+
text: str = radbtn_attr_dict["text"]
|
|
290
|
+
sub_ctrl = self._add_radiobutton(value, text)
|
|
291
|
+
# self._app.debug_print(f"{' '*(level + 1)}Control: Radiobutton, text: {text}", end="")
|
|
292
|
+
self._app.assemble_control(sub_ctrl, radbtn_attr_dict)
|
|
293
|
+
|
|
294
|
+
def _add_radiobutton(self, val: int, txt: str, **opt_dict: Any):
|
|
295
|
+
# radbutton = ttk.Radiobutton(self._parent, variable=self._var_val, **opt_dict)
|
|
296
|
+
radbutton = RadioButtonCtrl(super().control, self._owner, "",
|
|
297
|
+
text=txt, vartext=self._vartext, value=val, **opt_dict)
|
|
298
|
+
self._radbutton_lst.append(radbutton)
|
|
299
|
+
return radbutton
|
|
300
|
+
|
|
301
|
+
@override
|
|
302
|
+
def destroy(self):
|
|
303
|
+
# po(f"RadiobuttonGroupCtrl {self._idself} destroy")
|
|
304
|
+
for radbutton in self._radbutton_lst:
|
|
305
|
+
# self._debug_print(f"going to del {id_ctrl}")
|
|
306
|
+
radbutton.destroy()
|
|
307
|
+
self._radbutton_lst.clear()
|
|
308
|
+
super().destroy()
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
class NotebookCtrl(tkControl):
|
|
312
|
+
def __init__(self, parent: tk.Misc, app: WinBasic, owner: Dialog, idself: str, *,
|
|
313
|
+
subctrlcfg_list: list[et.Element], level: int, **options: Any):
|
|
314
|
+
ctrl = ttk.Notebook(parent, **options)
|
|
315
|
+
tkControl.__init__(self, parent, "", idself, ctrl)
|
|
316
|
+
# app.debug_print()
|
|
317
|
+
self._app: WinBasic = app
|
|
318
|
+
self._idself: str = idself
|
|
319
|
+
self._idctrl_list: list[str] = []
|
|
320
|
+
for subctrl_cfg in list(subctrlcfg_list):
|
|
321
|
+
id_, sub_ctrl = self._app.create_control(self,
|
|
322
|
+
subctrl_cfg, level + 1)
|
|
323
|
+
self._idctrl_list.append(id_)
|
|
324
|
+
# app.debug_print(f"tabCtrl: {subctrl_cfg.tag}")
|
|
325
|
+
subctrl =cast(tkControl, sub_ctrl).control
|
|
326
|
+
ctrl.add(subctrl, text=subctrl_cfg.attrib["text"])
|
|
327
|
+
for item in list(subctrl_cfg):
|
|
328
|
+
idctrl_list = self._app.create_controls(sub_ctrl, item,
|
|
329
|
+
level + 2, owner)
|
|
330
|
+
self._idctrl_list.extend(idctrl_list)
|
|
331
|
+
|
|
332
|
+
@override
|
|
333
|
+
def destroy(self):
|
|
334
|
+
# po(f"NotebookCtrl {self._idself} destroy")
|
|
335
|
+
for idctrl in self._idctrl_list:
|
|
336
|
+
self._app.delete_control(idctrl)
|
|
337
|
+
self._idctrl_list.clear()
|
|
338
|
+
super().destroy()
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
# TODO: not fininsed
|
|
342
|
+
class FrameCtrl(tkControl):
|
|
343
|
+
def __init__(self, parent: tk.Misc, idself: str, **options):
|
|
344
|
+
ctrl = tk.Frame(parent, **options)
|
|
345
|
+
tkControl.__init__(self, parent, "", idself, ctrl)
|
|
346
|
+
|
|
347
|
+
@override
|
|
348
|
+
def destroy(self):
|
|
349
|
+
# po(f"FrameCtrl {self._idself} destroy")
|
|
350
|
+
super().destroy()
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
# TODO: not fininsed
|
|
354
|
+
class LabelFrameCtrl(tkControl):
|
|
355
|
+
def __init__(self, parent: tk.Misc, title:str, idself: str, **options):
|
|
356
|
+
ctrl = ttk.LabelFrame(parent, text=title, **options)
|
|
357
|
+
tkControl.__init__(self, parent, title, idself, ctrl)
|
|
358
|
+
|
|
359
|
+
@override
|
|
360
|
+
def destroy(self):
|
|
361
|
+
# po(f"LabelFrameCtrl {self._idself} destroy")
|
|
362
|
+
super().destroy()
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
class ScrollableFrameCtrl(tkControl):
|
|
366
|
+
""" 智能滚动容器
|
|
367
|
+
"""
|
|
368
|
+
def __init__(self, parent: tk.Misc, app: WinBasic, idself: str,
|
|
369
|
+
width: int = 0, height: int = 0, **options: Any):
|
|
370
|
+
self._outter_frame: tk.Frame = tk.Frame(parent, **options)
|
|
371
|
+
|
|
372
|
+
# 配置网格布局权重,确保框架能扩展
|
|
373
|
+
_ = self._outter_frame.grid_rowconfigure(0, weight=1)
|
|
374
|
+
_ = self._outter_frame.grid_columnconfigure(0, weight=1)
|
|
375
|
+
|
|
376
|
+
self._os_type: str = platform.system()
|
|
377
|
+
self._update_after_id: str | None = None
|
|
378
|
+
|
|
379
|
+
# 创建画布
|
|
380
|
+
self._canvas: tk.Canvas = tk.Canvas(self._outter_frame, width=width, height=height,
|
|
381
|
+
highlightthickness=0, highlightbackground="#ccc", takefocus=True)
|
|
382
|
+
self._canvas.grid(row=0, column=0, sticky="nsew")
|
|
383
|
+
|
|
384
|
+
# 垂直滚动条
|
|
385
|
+
self._vscrollbar: ttk.Scrollbar = ttk.Scrollbar(self._outter_frame, orient="vertical",
|
|
386
|
+
command=self._canvas.yview)
|
|
387
|
+
self._vscrollbar.grid(row=0, column=1, sticky="ns")
|
|
388
|
+
self._vscrollbar.grid_remove() # 默认隐藏
|
|
389
|
+
_ = self._canvas.configure(yscrollcommand=self._vscrollbar.set)
|
|
390
|
+
|
|
391
|
+
# 水平滚动条
|
|
392
|
+
self._hscrollbar: ttk.Scrollbar = ttk.Scrollbar(self._outter_frame, orient="horizontal",
|
|
393
|
+
command=self._canvas.xview)
|
|
394
|
+
_ = self._hscrollbar.grid(row=1, column=0, sticky="ew")
|
|
395
|
+
self._hscrollbar.grid_remove() # 默认隐藏
|
|
396
|
+
_ = self._canvas.configure(xscrollcommand=self._hscrollbar.set)
|
|
397
|
+
|
|
398
|
+
# Create a frame inside the canvas which will be scrolled with it
|
|
399
|
+
self._inner_frame: tk.Frame = tk.Frame(self._canvas)
|
|
400
|
+
super().__init__(parent, "", idself, self._inner_frame)
|
|
401
|
+
|
|
402
|
+
# self._outter_frame.bindtags((self._outter_frame, self._canvas, "Frame", "all"))
|
|
403
|
+
# 调整bindtags,确保事件先传给自身,再传给画布
|
|
404
|
+
# self._inner_frame.bindtags((self._inner_frame, self._canvas, "Frame", "all"))
|
|
405
|
+
|
|
406
|
+
self._interior_id: int = self._canvas.create_window((0, 0),
|
|
407
|
+
window=self._inner_frame, anchor="nw")
|
|
408
|
+
|
|
409
|
+
# 绑定事件处理
|
|
410
|
+
_ = self._inner_frame.bind('<Configure>', self._on_configure_inner)
|
|
411
|
+
_ = self._canvas.bind('<Configure>', self._on_configure_canvas)
|
|
412
|
+
_ = self._inner_frame.bind("<Map>", self._on_map_inner)
|
|
413
|
+
|
|
414
|
+
# 鼠标滚轮支持
|
|
415
|
+
self._bind_scroll_events(self._canvas)
|
|
416
|
+
self._bind_scroll_events(self._inner_frame)
|
|
417
|
+
# self._bind_scroll_events(self._outter_frame)
|
|
418
|
+
|
|
419
|
+
# 初始更新
|
|
420
|
+
self._outter_frame.update_idletasks()
|
|
421
|
+
self._on_configure_inner(None)
|
|
422
|
+
|
|
423
|
+
def _bind_scroll_events(self, widget: tk.Widget):
|
|
424
|
+
"""为单个控件绑定所有必要的滚动事件"""
|
|
425
|
+
if self._os_type == "Linux":
|
|
426
|
+
vevents = ["<Button-4>", # 上滚
|
|
427
|
+
"<Button-5>"] # 下滚
|
|
428
|
+
hevents = ["<Shift-Button-4>", # 左滚
|
|
429
|
+
"<Shift-Button-5>"] # 右滚
|
|
430
|
+
else:
|
|
431
|
+
vevents = ["<MouseWheel>"] # 垂直滚动
|
|
432
|
+
hevents = ["<Shift-MouseWheel>"] # 水平滚动
|
|
433
|
+
if self._os_type == "Darwin":
|
|
434
|
+
hevents.append("<Command-MouseWheel>")
|
|
435
|
+
|
|
436
|
+
# 为控件绑定滚动事件处理函数
|
|
437
|
+
for event in vevents:
|
|
438
|
+
_ = widget.bind(event, self._on_vmousewheel)
|
|
439
|
+
for event in hevents:
|
|
440
|
+
_ = widget.bind(event, self._on_hmousewheel)
|
|
441
|
+
|
|
442
|
+
def update_layout(self) -> None:
|
|
443
|
+
"""公共方法:更新布局和滚动区域"""
|
|
444
|
+
self._on_configure_inner(None)
|
|
445
|
+
|
|
446
|
+
def _on_map_inner(self, event: tk.Event[tk.Frame]) -> None:
|
|
447
|
+
"""当内部控件被映射时强制更新布局"""
|
|
448
|
+
self._outter_frame.update_idletasks()
|
|
449
|
+
self._on_configure_inner(event)
|
|
450
|
+
|
|
451
|
+
def _on_configure_inner(self, event: tk.Event[tk.Frame] | None):
|
|
452
|
+
"""内容变化时更新滚动区域"""
|
|
453
|
+
|
|
454
|
+
self._outter_frame.update_idletasks()
|
|
455
|
+
|
|
456
|
+
# Update the scrollbars to match the size of the inner frame
|
|
457
|
+
width = self._inner_frame.winfo_reqwidth()
|
|
458
|
+
height = self._inner_frame.winfo_reqheight()
|
|
459
|
+
_ = self._canvas.config(scrollregion=(0, 0, width, height))
|
|
460
|
+
|
|
461
|
+
# if self._inner_frame.winfo_reqwidth() != self._canvas.winfo_width():
|
|
462
|
+
# Update the canvas's width to fit the inner frame
|
|
463
|
+
# _ = self._canvas.config(width=self._inner_frame.winfo_reqwidth())
|
|
464
|
+
|
|
465
|
+
# 垂直滚动条显示逻辑
|
|
466
|
+
canvas_height = self._canvas.winfo_height()
|
|
467
|
+
if height > canvas_height + 5:
|
|
468
|
+
_ = self._vscrollbar.grid()
|
|
469
|
+
else:
|
|
470
|
+
self._vscrollbar.grid_remove()
|
|
471
|
+
|
|
472
|
+
# 水平滚动条显示逻辑
|
|
473
|
+
canvas_width = self._canvas.winfo_width()
|
|
474
|
+
if width > canvas_width + 5:
|
|
475
|
+
_ = self._hscrollbar.grid()
|
|
476
|
+
else:
|
|
477
|
+
self._hscrollbar.grid_remove()
|
|
478
|
+
|
|
479
|
+
# 为所有子控件绑定滚动事件
|
|
480
|
+
for widget in self._inner_frame.winfo_children():
|
|
481
|
+
if not hasattr(widget, '_scroll_events_bound'):
|
|
482
|
+
self._bind_scroll_events(widget)
|
|
483
|
+
widget._scroll_events_bound = True # 标记为已绑定
|
|
484
|
+
|
|
485
|
+
def _on_configure_canvas(self, event: tk.Event[tk.Canvas]):
|
|
486
|
+
"""画布大小变化时调整"""
|
|
487
|
+
if self._inner_frame.winfo_reqwidth() != self._canvas.winfo_width():
|
|
488
|
+
# Update the inner frame's width to fill the canvas
|
|
489
|
+
_ = self._canvas.itemconfigure(self._interior_id, width=self._canvas.winfo_width())
|
|
490
|
+
# _ = self._canvas.itemconfig(self._interior_id, width=event.width)
|
|
491
|
+
if self._update_after_id is not None:
|
|
492
|
+
self._outter_frame.after_cancel(self._update_after_id)
|
|
493
|
+
|
|
494
|
+
self._update_after_id = self._outter_frame.after(30, self._on_configure_inner, None)
|
|
495
|
+
|
|
496
|
+
def _on_vmousewheel(self, event: tk.Event[tk.Misc]):
|
|
497
|
+
"""垂直滚动处理"""
|
|
498
|
+
if not self._vscrollbar.winfo_viewable():
|
|
499
|
+
return None
|
|
500
|
+
# po("_on_vmousewheel")
|
|
501
|
+
# if not self._vscrollbar.winfo_ismapped():
|
|
502
|
+
# return "break"
|
|
503
|
+
# delta = event.delta
|
|
504
|
+
# pv(delta)
|
|
505
|
+
# scroll_units = -1 if delta > 0 else 1
|
|
506
|
+
delta = event.delta if hasattr(event, 'delta') else -1 if event.num == 4 else 1
|
|
507
|
+
scroll_units = -int(delta / 120)
|
|
508
|
+
self._canvas.focus_set()
|
|
509
|
+
self._canvas.yview_scroll(scroll_units, "units")
|
|
510
|
+
# 阻止事件传播到其他组件
|
|
511
|
+
return "break"
|
|
512
|
+
|
|
513
|
+
def _on_hmousewheel(self, event: tk.Event[tk.Misc]):
|
|
514
|
+
"""水平滚动处理"""
|
|
515
|
+
if not self._hscrollbar.winfo_viewable():
|
|
516
|
+
return None
|
|
517
|
+
# po("_on_hmousewheel")
|
|
518
|
+
# self.update_layout()
|
|
519
|
+
|
|
520
|
+
# if not self._hscrollbar.winfo_ismapped():
|
|
521
|
+
# return "break"
|
|
522
|
+
|
|
523
|
+
_ = event.widget.focus_set()
|
|
524
|
+
|
|
525
|
+
delta = event.delta if hasattr(event, 'delta') else -1 if event.num == 4 else 1
|
|
526
|
+
scroll_units = -int(delta / 120)
|
|
527
|
+
_ = self._canvas.xview_scroll(scroll_units, "units")
|
|
528
|
+
# 阻止事件传播到其他组件
|
|
529
|
+
return "break"
|
|
530
|
+
|
|
531
|
+
@property
|
|
532
|
+
def outter(self):
|
|
533
|
+
return self._outter_frame
|
|
534
|
+
|
|
535
|
+
@override
|
|
536
|
+
def destroy(self):
|
|
537
|
+
# po(f"ScrollableFrame {self._idself} destroy")
|
|
538
|
+
self._inner_frame.destroy()
|
|
539
|
+
self._vscrollbar.destroy()
|
|
540
|
+
self._hscrollbar.destroy()
|
|
541
|
+
self._canvas.destroy()
|
|
542
|
+
super().destroy()
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
# TODO: 1. Tip
|
|
546
|
+
class PicsListviewCtrl(tkControl):
|
|
547
|
+
def __init__(self, parent: tk.Misc, app: WinBasic, owner: Dialog, idself: str,
|
|
548
|
+
num_column: int, pic_size: int, res_path: str):
|
|
549
|
+
ctrl = ttk.Frame(parent)
|
|
550
|
+
tkControl.__init__(self, parent, "", idself, ctrl)
|
|
551
|
+
self._image_group: list[ttk.LabelFrame] = []
|
|
552
|
+
self._imagepanel_llist: list[list[ImagePanelCtrl]] = []
|
|
553
|
+
self._app: WinBasic = app
|
|
554
|
+
self._owner: Dialog = owner
|
|
555
|
+
self._num_column: int = num_column
|
|
556
|
+
self._pic_size: int = pic_size
|
|
557
|
+
self._res_path: str = res_path
|
|
558
|
+
self._grp_seld: int = 0
|
|
559
|
+
self._idx_seld: int = 0
|
|
560
|
+
self._idx_lstseld: list[int] = [0, 0]
|
|
561
|
+
self._spacing: int = int(self._pic_size/10)
|
|
562
|
+
self._groupidx: int = 0
|
|
563
|
+
|
|
564
|
+
def add_imagegroup(self, title: str, imagefile_list: list[str]):
|
|
565
|
+
frame = ttk.LabelFrame(self._tkctrl, text=title)
|
|
566
|
+
imagepanel_list: list[ImagePanelCtrl] = []
|
|
567
|
+
for i, imagefile in enumerate(imagefile_list):
|
|
568
|
+
imagefile = os.path.join(self._res_path, imagefile)
|
|
569
|
+
image_panel = ImagePanelCtrl(frame, "", imagefile,
|
|
570
|
+
width=self._pic_size, height=self._pic_size)
|
|
571
|
+
image_panel.control.grid(row=i // self._num_column, column=i % self._num_column,
|
|
572
|
+
padx=self._spacing, pady=self._spacing)
|
|
573
|
+
_= image_panel.control.bind("<Button-1>",
|
|
574
|
+
lambda e, grp=self._groupidx, idx=i: self.select(grp, idx))
|
|
575
|
+
imagepanel_list.append(image_panel)
|
|
576
|
+
self._imagepanel_llist.append(imagepanel_list)
|
|
577
|
+
frame.pack()
|
|
578
|
+
self._image_group.append(frame)
|
|
579
|
+
self._groupidx += 1
|
|
580
|
+
|
|
581
|
+
def select(self, grp:int, idx: int):
|
|
582
|
+
self._idx_lstseld = [self._grp_seld, self._idx_seld]
|
|
583
|
+
self._grp_seld = grp
|
|
584
|
+
self._idx_seld = idx
|
|
585
|
+
|
|
586
|
+
old_imagepanle = self._imagepanel_llist[self._idx_lstseld[0]][self._idx_lstseld[1]]
|
|
587
|
+
_ = old_imagepanle.configure(highlightthickness=0)
|
|
588
|
+
imagepanel = self._imagepanel_llist[self._grp_seld][self._idx_seld]
|
|
589
|
+
_ = imagepanel.configure(highlightbackground="blue", highlightthickness=2)
|
|
590
|
+
_ = self._owner.process_message(self._idself, event="clicked",
|
|
591
|
+
group=self._grp_seld, index=self._idx_seld)
|
|
592
|
+
|
|
593
|
+
def get_selected(self) -> tuple[int, int]:
|
|
594
|
+
return self._grp_seld, self._idx_seld
|
|
595
|
+
|
|
596
|
+
@override
|
|
597
|
+
def destroy(self):
|
|
598
|
+
# po(f"PicsListviewCtrl {self._idself} destroy")
|
|
599
|
+
for group in self._imagepanel_llist:
|
|
600
|
+
for image in group:
|
|
601
|
+
image.destroy()
|
|
602
|
+
self._imagepanel_llist.clear()
|
|
603
|
+
for frm in self._image_group:
|
|
604
|
+
frm.destroy()
|
|
605
|
+
self._image_group.clear()
|
|
606
|
+
self._tkctrl.destroy()
|
|
607
|
+
self._grp_seld = 0
|
|
608
|
+
self._idx_seld = 0
|
|
609
|
+
super().destroy()
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
class ToolbarCtrl(tkControl):
|
|
613
|
+
def __init__(self, parent: tk.Misc, app: WinBasic, res_path: str,
|
|
614
|
+
subctrls: list[et.Element], **options):
|
|
615
|
+
ctrl = ttk.Frame(parent, **options)
|
|
616
|
+
tkControl.__init__(self, parent, "", "", ctrl)
|
|
617
|
+
self._res_path: str = res_path
|
|
618
|
+
self._app: WinBasic = app
|
|
619
|
+
self._idctrl_list: list[str] = []
|
|
620
|
+
for subctrl in subctrls:
|
|
621
|
+
idctrl_list = self._app.create_controls(self, subctrl, 1)
|
|
622
|
+
self._idctrl_list.extend(idctrl_list)
|
|
623
|
+
|
|
624
|
+
@override
|
|
625
|
+
def destroy(self):
|
|
626
|
+
for idctrl in self._idctrl_list:
|
|
627
|
+
self._app.delete_control(idctrl)
|
|
628
|
+
self._idctrl_list.clear()
|
|
629
|
+
super().destroy()
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
T = TypeVar("T", bound=tk.Tk | tk.Toplevel)
|
|
633
|
+
class tkWM(Generic[T], Widget):
|
|
634
|
+
def __init__(self, wm: T):
|
|
635
|
+
super().__init__()
|
|
636
|
+
self._tkwm: T = wm
|
|
637
|
+
|
|
638
|
+
@property
|
|
639
|
+
def control(self):
|
|
640
|
+
return self._tkwm
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
# TODO: auto scrollable or not
|
|
644
|
+
class DialogCtrl(Dialog):
|
|
645
|
+
def __init__(self, app: tkWin, dlg_cfg: et.Element):
|
|
646
|
+
attr_dict = dlg_cfg.attrib
|
|
647
|
+
super().__init__(attr_dict.get("text", ""), int(attr_dict["Width"]), height=int(attr_dict["Height"]))
|
|
648
|
+
# options: dict[str, Any] = {}
|
|
649
|
+
# if "options" in attr_dict:
|
|
650
|
+
# options = eval(attr_dict["options"])
|
|
651
|
+
self._parent: tk.Tk | tk.Toplevel = app.win
|
|
652
|
+
# self._owner: Dialog | None = None
|
|
653
|
+
self._xx: int = 0
|
|
654
|
+
self._yy: int = 0
|
|
655
|
+
self._top: tkWM[tk.Toplevel] | None = None
|
|
656
|
+
self._app: tkWin = app
|
|
657
|
+
self._alive: bool = False
|
|
658
|
+
self._idself: str = attr_dict["id"]
|
|
659
|
+
self._subctrlcfg_list: list[et.Element] = list(dlg_cfg)
|
|
660
|
+
self._idctrl_list: list[str] = []
|
|
661
|
+
self._extral_msg: dict[str, object] = {}
|
|
662
|
+
|
|
663
|
+
# @property
|
|
664
|
+
# def owner(self):
|
|
665
|
+
# if self._owner is not None:
|
|
666
|
+
# return self._owner
|
|
667
|
+
# else:
|
|
668
|
+
# return self._app
|
|
669
|
+
|
|
670
|
+
@override
|
|
671
|
+
def set_title(self, val: str):
|
|
672
|
+
super().set_title(val)
|
|
673
|
+
if self._top is not None:
|
|
674
|
+
self._top.control.title(self._title)
|
|
675
|
+
|
|
676
|
+
@property
|
|
677
|
+
def alive(self):
|
|
678
|
+
return self._alive
|
|
679
|
+
|
|
680
|
+
def do_show(self, owner: Container | None = None, x: int = 0, y: int = 0, **kwargs: object):
|
|
681
|
+
# po(f"show Dialog {self._idself}: {kwargs}")
|
|
682
|
+
# self.deiconify()
|
|
683
|
+
self._alive = True
|
|
684
|
+
if owner is not None:
|
|
685
|
+
self._owner = owner
|
|
686
|
+
|
|
687
|
+
self._top = tkWM[tk.Toplevel](tk.Toplevel(self._parent))
|
|
688
|
+
|
|
689
|
+
# x, y, _, _ = self._app.get_winsize()
|
|
690
|
+
if owner is not None:
|
|
691
|
+
self._xx = x
|
|
692
|
+
self._yy = y
|
|
693
|
+
else:
|
|
694
|
+
self._xx = self._parent.winfo_rootx() + x
|
|
695
|
+
self._yy = self._parent.winfo_rooty() + y
|
|
696
|
+
# pv(self.pos)
|
|
697
|
+
|
|
698
|
+
self._top.control.geometry(f'{self._ww}x{self._hh}+{self._xx}+{self._yy}')
|
|
699
|
+
|
|
700
|
+
# self.withdraw()
|
|
701
|
+
iddlg = self._idself
|
|
702
|
+
|
|
703
|
+
frmdlg_xml = self._app.create_xml("Top", {})
|
|
704
|
+
|
|
705
|
+
id_frmain = f"frmMain{iddlg}"
|
|
706
|
+
# frmain_xml = self._app.create_xml("Frame", {"id": id_frmain}, frmdlg_xml)
|
|
707
|
+
frmain_xml = self._app.create_xml("ScrollableFrame", {"id": id_frmain,
|
|
708
|
+
"Width": f"{self._ww-30}", "Height": f"{self._hh-160}"}, frmdlg_xml)
|
|
709
|
+
_, frmmain_ctrl = self._app.create_control(self._top,
|
|
710
|
+
frmain_xml, 0, self)
|
|
711
|
+
# self._idctrl_list.append(id_frmain)
|
|
712
|
+
self._idctrl_dict[id_frmain] = frmmain_ctrl
|
|
713
|
+
# frm_main = cast(tkControl, frmmain).control
|
|
714
|
+
# frm_main = cast(tkControl, frmmain_ctrl)
|
|
715
|
+
|
|
716
|
+
for sub_ctrl in self._subctrlcfg_list:
|
|
717
|
+
subidctrl_dict = self._app.create_controls(frmmain_ctrl, sub_ctrl, 1, self)
|
|
718
|
+
# self._idctrl_list.extend(subidctrl_list)
|
|
719
|
+
self._idctrl_dict.update(subidctrl_dict)
|
|
720
|
+
|
|
721
|
+
_ = self._app.assemble_control(frmmain_ctrl, {"layout": "pack",
|
|
722
|
+
"pack": "{'side':'top','fill':'both','expand':True,'padx':5,'pady':5}"})
|
|
723
|
+
|
|
724
|
+
frmbot_xml = self._app.create_xml("Frame", {"id": f"frmBot{iddlg}"}, frmdlg_xml)
|
|
725
|
+
id_frmbot, frmbot_ctrl = self._app.create_control(self._top,
|
|
726
|
+
frmbot_xml, 0, self)
|
|
727
|
+
# self._idctrl_list.append(id_frmbot)
|
|
728
|
+
self._idctrl_dict[id_frmbot] = frmbot_ctrl
|
|
729
|
+
|
|
730
|
+
btnConfirm_xml = self._app.create_xml("Button", {"id": f"btnConfirm{iddlg}",
|
|
731
|
+
"text": "Confirm", "options": "{'width':20}"}, frmbot_xml)
|
|
732
|
+
id_btnconfirm, btnConfirm_ctrl = self._app.create_control(frmbot_ctrl,
|
|
733
|
+
btnConfirm_xml, 1, self)
|
|
734
|
+
# self._idctrl_list.append(idctrl)
|
|
735
|
+
self._idctrl_dict[id_btnconfirm] = btnConfirm_ctrl
|
|
736
|
+
_ = self._app.assemble_control(btnConfirm_ctrl, {"layout":"pack",
|
|
737
|
+
"pack":"{'side':'right','fill':'both','expand':True,'padx':5,'pady':5}"}, f"{' '*1}")
|
|
738
|
+
|
|
739
|
+
bntcancel_xml = self._app.create_xml("Button", {"id": f"btnCancel{iddlg}",
|
|
740
|
+
"text": "Cancel", "options": "{'width':20}"}, frmbot_xml)
|
|
741
|
+
id_btncancel, btncancel_ctrl = self._app.create_control(frmbot_ctrl,
|
|
742
|
+
bntcancel_xml, 1, self)
|
|
743
|
+
# self._idctrl_list.append(idctrl)
|
|
744
|
+
self._idctrl_dict[id_btncancel] = btncancel_ctrl
|
|
745
|
+
# pv(self._idctrl_list)
|
|
746
|
+
_ = self._app.assemble_control(btncancel_ctrl, {"layout":"pack",
|
|
747
|
+
"pack":"{'side':'right','fill':'both','expand':True,'padx':5,'pady':5}"}, f"{' '*1}")
|
|
748
|
+
|
|
749
|
+
_ = self._app.assemble_control(frmbot_ctrl, {"layout": "pack",
|
|
750
|
+
"pack": "{'side':'bottom','fill':'x','expand':True,'padx':5,'pady':5}"})
|
|
751
|
+
|
|
752
|
+
self._extral_msg = kwargs
|
|
753
|
+
_ = self.process_message("beforego", **kwargs)
|
|
754
|
+
|
|
755
|
+
self._top.control.title(self._title)
|
|
756
|
+
|
|
757
|
+
# Disable the window's resizing capability
|
|
758
|
+
_ = self._top.control.resizable(width=tk.FALSE, height=tk.FALSE)
|
|
759
|
+
# self._top.wait_visibility() # can't grab until window appears, so we wait
|
|
760
|
+
self._top.control.transient(self._parent) # dialog window is related to main
|
|
761
|
+
self._top.control.protocol("WM_DELETE_WINDOW", self.destroy) # intercept close button
|
|
762
|
+
|
|
763
|
+
# Container.register_eventhandler(self, id_btncancel, self._do_cancel)
|
|
764
|
+
self.register_eventhandler(id_btncancel, self._do_cancel)
|
|
765
|
+
# Container.register_eventhandler(self, id_btnconfirm, self._do_confirm)
|
|
766
|
+
self.register_eventhandler(id_btnconfirm, self._do_confirm)
|
|
767
|
+
|
|
768
|
+
# if self._owner is not None:
|
|
769
|
+
# self._owner.back()
|
|
770
|
+
super().back(False)
|
|
771
|
+
|
|
772
|
+
# 设置achieved_value,使该窗口始终处于其他窗口的上层
|
|
773
|
+
_ = self._top.control.wm_attributes("-topmost", True) # pyright: ignore[reportUnknownMemberType]
|
|
774
|
+
self._top.control.grab_set() # ensure all input goes to our window
|
|
775
|
+
self._top.control.wm_deiconify()
|
|
776
|
+
# self._parent.wait_window(self._top)
|
|
777
|
+
self._top.control.wait_window()
|
|
778
|
+
# pv(self._id_list)
|
|
779
|
+
|
|
780
|
+
def get_control(self, idctrl: str) -> object:
|
|
781
|
+
return self._app.get_control(idctrl)
|
|
782
|
+
|
|
783
|
+
def _do_cancel(self, **kwargs: object):
|
|
784
|
+
# po(f"Dialog {self._idself} _do_cancel")
|
|
785
|
+
self.destroy(confirm=False, **kwargs)
|
|
786
|
+
|
|
787
|
+
def _do_confirm(self, **kwargs: object):
|
|
788
|
+
# po(f"Dialog {self._idself} _do_confirm")
|
|
789
|
+
self.destroy(confirm=True, **kwargs)
|
|
790
|
+
|
|
791
|
+
@override
|
|
792
|
+
def process_message(self, idmsg: str, **kwargs: object):
|
|
793
|
+
kwargs.update(self._extral_msg)
|
|
794
|
+
return super().process_message(idmsg, **kwargs)
|
|
795
|
+
|
|
796
|
+
@override
|
|
797
|
+
def destroy(self, **kwargs: object):
|
|
798
|
+
# po(f"Dialog {self._idself} destroy")
|
|
799
|
+
# pv(kwargs)
|
|
800
|
+
confirm = cast(bool, kwargs.get("confirm", False))
|
|
801
|
+
if self._top:
|
|
802
|
+
if confirm:
|
|
803
|
+
ret, msg = cast(tuple[bool, str],
|
|
804
|
+
super().process_message("confirm", **kwargs))
|
|
805
|
+
if not ret:
|
|
806
|
+
self._app.show_err(self._title, msg)
|
|
807
|
+
return
|
|
808
|
+
else:
|
|
809
|
+
_ = self.process_message("cancel", **kwargs)
|
|
810
|
+
try:
|
|
811
|
+
before_close = cast(EventHanlder, getattr(
|
|
812
|
+
self, "_before_close"
|
|
813
|
+
)) # get before_close from child
|
|
814
|
+
ret, msg = cast(tuple[bool, str],before_close(**kwargs))
|
|
815
|
+
if not ret:
|
|
816
|
+
self._app.show_err(self._title, msg)
|
|
817
|
+
return
|
|
818
|
+
except AttributeError as r:
|
|
819
|
+
# po(f"Warnning: {self._title} to exit, because {r}")
|
|
820
|
+
print(f"Warnning: {self._title} to exit, because {r}")
|
|
821
|
+
|
|
822
|
+
self._top.control.grab_release()
|
|
823
|
+
super().back()
|
|
824
|
+
# for idctrl in self._idctrl_list:
|
|
825
|
+
for idctrl, _ in self._idctrl_dict.items():
|
|
826
|
+
self._app.delete_control(idctrl)
|
|
827
|
+
# po("subctrl have been deleted!")
|
|
828
|
+
# self._idctrl_list.clear()
|
|
829
|
+
self._idctrl_dict.clear()
|
|
830
|
+
self._top.control.destroy()
|
|
831
|
+
self._top = None
|
|
832
|
+
self._alive = False
|
|
833
|
+
# if self._owner is not None:
|
|
834
|
+
# self._owner.back(False)
|
|
835
|
+
super().destroy()
|
|
836
|
+
|
|
837
|
+
_T_contra = TypeVar("_T_contra", contravariant=True)
|
|
838
|
+
class SupportsWrite(Protocol[_T_contra]):
|
|
839
|
+
"""自定义协议:表示支持 write(str) 方法的对象"""
|
|
840
|
+
def write(self, s: str) -> object: ...
|
|
841
|
+
|
|
842
|
+
|
|
843
|
+
# class Root(tkControl):
|
|
844
|
+
# def __init__(self):
|
|
845
|
+
# self._win: tk.Tk = tk.Tk()
|
|
846
|
+
# super().__init__(self._win, "", "", self._win)
|
|
847
|
+
|
|
848
|
+
|
|
849
|
+
class tkWin(WinBasic):
|
|
850
|
+
def __init__(self, cur_path: str, xmlfile: str):
|
|
851
|
+
super().__init__(xmlfile)
|
|
852
|
+
self._is_debug: bool = False
|
|
853
|
+
|
|
854
|
+
# Windows提前启用DPI感知
|
|
855
|
+
if sys.platform.startswith("win"):
|
|
856
|
+
try:
|
|
857
|
+
ctypes.windll.shcore.SetProcessDpiAwareness(1)
|
|
858
|
+
except Exception:
|
|
859
|
+
pass
|
|
860
|
+
# self._win: tk.Tk = tk.Tk()
|
|
861
|
+
self._root: tkWM[tk.Tk] = tkWM[tk.Tk](tk.Tk())
|
|
862
|
+
self._win: tk.Tk = self._root.control
|
|
863
|
+
|
|
864
|
+
"""
|
|
865
|
+
if IS_WINDOWS:
|
|
866
|
+
try: # >= win 8.1
|
|
867
|
+
ctypes.windll.shcore.SetProcessDpiAwareness(2)
|
|
868
|
+
except: # win 8.0 or less
|
|
869
|
+
ctypes.windll.user32.SetProcessDPIAware()
|
|
870
|
+
# ctypes.windll.shcore.SetProcessDpiAwareness(1)
|
|
871
|
+
scale_fact = cast(float, ctypes.windll.shcore.GetScaleFactorForDevice(0))
|
|
872
|
+
pv(scale_fact)
|
|
873
|
+
self._win.tk.call("tk", "scaling", scale_fact / 90)
|
|
874
|
+
"""
|
|
875
|
+
self._scale_factor: float = self._get_scale_factor()
|
|
876
|
+
self._win.tk.call("tk", "scaling", self._scale_factor)
|
|
877
|
+
|
|
878
|
+
exit_window = partial(self.exit)
|
|
879
|
+
self._win.protocol("WM_DELETE_WINDOW", exit_window)
|
|
880
|
+
# 注册(绑定)窗口变动事件
|
|
881
|
+
_ = self._win.bind('<Configure>', self._on_winresize)
|
|
882
|
+
_ = self._win.bind_all("<KeyPress>", self._on_keypress)
|
|
883
|
+
# _ = self._win.bind_all("<MouseWheel>", self._on_mousewheel)
|
|
884
|
+
# self._win.bind("<Motion>", self._motion)
|
|
885
|
+
# self._win.bind("<Button-1>", self._mouseclicked)
|
|
886
|
+
# self._win.columnconfigure(0, weight=1)
|
|
887
|
+
# self._win.rowconfigure(0, weight=1)
|
|
888
|
+
|
|
889
|
+
self._cur_path: str = cur_path
|
|
890
|
+
self._res_path: str = os.path.dirname(xmlfile)
|
|
891
|
+
|
|
892
|
+
# self._mousex: int = 0
|
|
893
|
+
# self._mousey: int = 0
|
|
894
|
+
|
|
895
|
+
self.set_title(self._title)
|
|
896
|
+
self.create_window()
|
|
897
|
+
|
|
898
|
+
def _get_scale_factor(self):
|
|
899
|
+
"""获取系统缩放比例(默认1.0)"""
|
|
900
|
+
try:
|
|
901
|
+
if sys.platform.startswith("win"):
|
|
902
|
+
# Windows:通过系统API获取缩放比例
|
|
903
|
+
user32 = ctypes.windll.user32
|
|
904
|
+
dpi = cast(float, user32.GetDpiForWindow(user32.GetForegroundWindow()))
|
|
905
|
+
return dpi / 96.0 # 96 DPI为默认缩放(100%)
|
|
906
|
+
elif sys.platform == "darwin":
|
|
907
|
+
# macOS:通过Tk内置方法获取
|
|
908
|
+
return cast(float, self._win.tk.call("tk", "scaling"))
|
|
909
|
+
else:
|
|
910
|
+
# Linux:假设使用1.0或通过xdpyinfo获取(简化处理)
|
|
911
|
+
return 1.0
|
|
912
|
+
except Exception:
|
|
913
|
+
return 1.0 # 异常时使用默认值
|
|
914
|
+
|
|
915
|
+
@property
|
|
916
|
+
def win(self):
|
|
917
|
+
return self._win
|
|
918
|
+
|
|
919
|
+
@property
|
|
920
|
+
def path(self):
|
|
921
|
+
return self._cur_path
|
|
922
|
+
|
|
923
|
+
def debug_print(self, *args: object, **kwargs: object):
|
|
924
|
+
if self._is_debug:
|
|
925
|
+
__builtin__.print(*args, **kwargs)
|
|
926
|
+
|
|
927
|
+
def _center_window(self, width: int, hight: int):
|
|
928
|
+
"""设置窗口居中和宽高
|
|
929
|
+
|
|
930
|
+
Args:
|
|
931
|
+
width (int): 窗口宽度
|
|
932
|
+
hight (int): 窗口高度
|
|
933
|
+
|
|
934
|
+
Returns:
|
|
935
|
+
None
|
|
936
|
+
"""
|
|
937
|
+
# 获取屏幕宽度和高度
|
|
938
|
+
sw = self._win.winfo_screenwidth()
|
|
939
|
+
sh = self._win.winfo_screenheight()
|
|
940
|
+
|
|
941
|
+
# 计算中心坐标
|
|
942
|
+
cen_x = int((sw - width) / 2)
|
|
943
|
+
cen_y = int((sh - hight) / 2)
|
|
944
|
+
|
|
945
|
+
self._xx: int = cen_x
|
|
946
|
+
self._yy: int = cen_y
|
|
947
|
+
|
|
948
|
+
# 设置窗口大小并居中
|
|
949
|
+
self._win.geometry(f"{width}x{hight}+{cen_x}+{cen_y}")
|
|
950
|
+
|
|
951
|
+
@override
|
|
952
|
+
def set_title(self, val: str):
|
|
953
|
+
super().set_title(val)
|
|
954
|
+
self._win.title(self._title)
|
|
955
|
+
|
|
956
|
+
@override
|
|
957
|
+
def create_window(self):
|
|
958
|
+
if self._ww and self._hh:
|
|
959
|
+
self._center_window(self._ww, self._hh)
|
|
960
|
+
|
|
961
|
+
for frm in list(self._wincfg):
|
|
962
|
+
# _ = self.create_controls(self._win, frm)
|
|
963
|
+
_ = self.create_controls(self._root, frm)
|
|
964
|
+
|
|
965
|
+
@override
|
|
966
|
+
def create_control(self, parent: Widget, ctrl_cfg: et.Element,
|
|
967
|
+
level: int = 0, owner: Dialog | None = None) -> tuple[str, Widget]:
|
|
968
|
+
if owner is None:
|
|
969
|
+
owner = self
|
|
970
|
+
tag = ctrl_cfg.tag
|
|
971
|
+
attr_dict = ctrl_cfg.attrib
|
|
972
|
+
text: str | None = attr_dict.get("text")
|
|
973
|
+
idctrl: str = ""
|
|
974
|
+
if "id" in attr_dict:
|
|
975
|
+
idctrl = attr_dict["id"]
|
|
976
|
+
elif text is not None:
|
|
977
|
+
idctrl = text.replace(" ", "").replace(".", "_").replace("\n", "_")
|
|
978
|
+
else:
|
|
979
|
+
raise RuntimeError("No id")
|
|
980
|
+
self.debug_print(f"{' '*level}{tag}, id: {idctrl}, text: {text}", end="")
|
|
981
|
+
|
|
982
|
+
if idctrl in self._idctrl_dict:
|
|
983
|
+
raise KeyError(f"{idctrl} already exists")
|
|
984
|
+
|
|
985
|
+
options: dict[str, Any] = {}
|
|
986
|
+
if "options" in attr_dict:
|
|
987
|
+
options = eval(attr_dict["options"])
|
|
988
|
+
|
|
989
|
+
# pe(type(parent))
|
|
990
|
+
if issubclass(type(parent), tkControl):
|
|
991
|
+
master = cast(tkControl, parent).control
|
|
992
|
+
# elif type(parent) is tkWM[tk.Tk]:
|
|
993
|
+
# master = parent.control
|
|
994
|
+
# elif type(parent) is tkWM[tk.Toplevel]:
|
|
995
|
+
# master = parent.control
|
|
996
|
+
elif isinstance(parent, tkWM):
|
|
997
|
+
# typ = get_args(get_origin(parent))
|
|
998
|
+
# if typ == tuple[tk.Tk]:
|
|
999
|
+
master = parent.control
|
|
1000
|
+
elif tag == "Menu":
|
|
1001
|
+
master = self._win
|
|
1002
|
+
else:
|
|
1003
|
+
# master = cast(tk.Widget, parent)
|
|
1004
|
+
raise ValueError(f"{tag}: unknown Control")
|
|
1005
|
+
|
|
1006
|
+
match tag:
|
|
1007
|
+
case "LabelFrame":
|
|
1008
|
+
assert text is not None
|
|
1009
|
+
# ctrl = ttk.LabelFrame(master, text=text, **options)
|
|
1010
|
+
ctrl = LabelFrameCtrl(master, text, idctrl, **options)
|
|
1011
|
+
self.debug_print()
|
|
1012
|
+
case "Frame" | "Tab":
|
|
1013
|
+
ctrl = FrameCtrl(master, idctrl, **options)
|
|
1014
|
+
self.debug_print()
|
|
1015
|
+
case "ScrollableFrame":
|
|
1016
|
+
ctrl = ScrollableFrameCtrl(master, self, idctrl,
|
|
1017
|
+
int(attr_dict["Width"]), int(attr_dict["Height"]),
|
|
1018
|
+
**options)
|
|
1019
|
+
self.debug_print()
|
|
1020
|
+
case "Label":
|
|
1021
|
+
assert text is not None
|
|
1022
|
+
# clickable = cast(bool, attr_dict.get("clickable", False))
|
|
1023
|
+
clickable = True if "clickable" in attr_dict else False
|
|
1024
|
+
# po(f"create {idctrl}: {options}")
|
|
1025
|
+
ctrl = LabelCtrl(master, owner, idctrl, text, clickable, **options)
|
|
1026
|
+
case "Button":
|
|
1027
|
+
assert text is not None
|
|
1028
|
+
ctrl = ButtonCtrl(master, owner, idctrl, text, **options)
|
|
1029
|
+
# TODO
|
|
1030
|
+
case "Canvas":
|
|
1031
|
+
ctrl = tk.Canvas(master, **options)
|
|
1032
|
+
case "Combobox":
|
|
1033
|
+
ctrl = ComboboxCtrl(master, owner,
|
|
1034
|
+
idself=idctrl,
|
|
1035
|
+
default=int(attr_dict["default"]),
|
|
1036
|
+
**options)
|
|
1037
|
+
case "Entry":
|
|
1038
|
+
ctrl = EntryCtrl(master, **options)
|
|
1039
|
+
if text is not None:
|
|
1040
|
+
ctrl.set_val(text)
|
|
1041
|
+
case "ImageButton":
|
|
1042
|
+
ctrl = ImageBtttonCtrl(master, owner, idctrl,
|
|
1043
|
+
respath=self._res_path, imagefile=attr_dict["image"],
|
|
1044
|
+
text=text, **options)
|
|
1045
|
+
case "ImagePanel":
|
|
1046
|
+
image = attr_dict.get("image", "")
|
|
1047
|
+
if image:
|
|
1048
|
+
image = os.path.join(self._res_path, image)
|
|
1049
|
+
ctrl = ImagePanelCtrl(master, idctrl, image, **options)
|
|
1050
|
+
case "MatPlot":
|
|
1051
|
+
assert text is not None
|
|
1052
|
+
if "size" in attr_dict:
|
|
1053
|
+
size = cast(tuple[float, float], literal_eval(attr_dict["size"]))
|
|
1054
|
+
ctrl = MatPlotCtrl(master, idctrl, text, attr_dict["xLabel"],
|
|
1055
|
+
attr_dict["yLabel"], size)
|
|
1056
|
+
else:
|
|
1057
|
+
ctrl = MatPlotCtrl(master, idctrl, text, attr_dict["xLabel"],
|
|
1058
|
+
attr_dict["yLabel"])
|
|
1059
|
+
case "Menu":
|
|
1060
|
+
self.debug_print()
|
|
1061
|
+
ctrl = self.create_menu(ctrl_cfg, **options)
|
|
1062
|
+
_ = self._win.config(menu=ctrl)
|
|
1063
|
+
case "RadiobuttonGroup":
|
|
1064
|
+
assert text is not None
|
|
1065
|
+
ctrl = RadioButtonGroupCtrl(master, self, owner, idctrl,
|
|
1066
|
+
text=text, subctrlcfg=ctrl_cfg,
|
|
1067
|
+
level=level, **options)
|
|
1068
|
+
self.debug_print()
|
|
1069
|
+
case "Radiobutton":
|
|
1070
|
+
assert text is not None
|
|
1071
|
+
if "var" in attr_dict:
|
|
1072
|
+
var_text = "_" + attr_dict["var"]
|
|
1073
|
+
else:
|
|
1074
|
+
var_text = "_var" + attr_dict["text"].replace(" ", "") \
|
|
1075
|
+
.replace(".", "_").replace("\n", "_")
|
|
1076
|
+
val = int(attr_dict["value"])
|
|
1077
|
+
ctrl = RadioButtonCtrl(master, owner, idctrl,
|
|
1078
|
+
text=text, vartext=var_text, value=val, **options)
|
|
1079
|
+
case "Checkbutton":
|
|
1080
|
+
assert text is not None
|
|
1081
|
+
if "var" in attr_dict:
|
|
1082
|
+
vartext = attr_dict["var"]
|
|
1083
|
+
else:
|
|
1084
|
+
vartext = attr_dict["text"].replace(" ", "").replace(".", "_").replace("\n", "_")
|
|
1085
|
+
# sel = cast(bool, literal_eval(attr_dict.get("select", "False")))
|
|
1086
|
+
sel = True if "select" in attr_dict else False
|
|
1087
|
+
ctrl = CheckButtonCtrl(master, self, idctrl,
|
|
1088
|
+
text=text, vartext=vartext, select=sel, **options)
|
|
1089
|
+
case "SlideSwitch":
|
|
1090
|
+
ctrl = SlideSwitchCtrl(master, owner, idctrl, **options)
|
|
1091
|
+
case "Calendar":
|
|
1092
|
+
ctrl = CalendarCtrl(master, owner, idctrl, **options)
|
|
1093
|
+
case "ScrollPicker":
|
|
1094
|
+
typ = __builtins__.get(attr_dict["type"], int)
|
|
1095
|
+
initial = attr_dict.get("initial", None)
|
|
1096
|
+
bg = attr_dict.get("background", "white")
|
|
1097
|
+
if 'value_list' in options:
|
|
1098
|
+
val_list = [typ(v) for v in options["value_list"]]
|
|
1099
|
+
else:
|
|
1100
|
+
start = int(options["start"])
|
|
1101
|
+
end = int(options['end'])
|
|
1102
|
+
val_list = list(range(start, end+1))
|
|
1103
|
+
ctrl = ScrollPickerCtrl[typ](master, owner, idctrl,
|
|
1104
|
+
int(attr_dict["width"]), int(attr_dict["height"]), val_list, initial, bg)
|
|
1105
|
+
case "TimeScrollPicker":
|
|
1106
|
+
ctrl = TimeScrollPickerCtrl(master, owner, idctrl, **options)
|
|
1107
|
+
case "Statusbar":
|
|
1108
|
+
ctrl = MultiStatusBar(master, **options)
|
|
1109
|
+
# for subctrl_cfg in list(ctrl_cfg):
|
|
1110
|
+
# ctrl.set_label(**subctrl_cfg.attrib)
|
|
1111
|
+
# TODO
|
|
1112
|
+
case "ScrolledText":
|
|
1113
|
+
ctrl = scrolledtext.ScrolledText(master, **options)
|
|
1114
|
+
# TODO
|
|
1115
|
+
case "Spinbox":
|
|
1116
|
+
ctrl = tk.Spinbox(master,
|
|
1117
|
+
command=lambda: self.process_message(idctrl, event="Changed"),
|
|
1118
|
+
**options)
|
|
1119
|
+
# TODO
|
|
1120
|
+
case "Style":
|
|
1121
|
+
ctrl = ttk.Style()
|
|
1122
|
+
ctrl.configure(text, **options)
|
|
1123
|
+
case "Toolbar":
|
|
1124
|
+
ctrl = ToolbarCtrl(master, self, self._res_path,
|
|
1125
|
+
list(ctrl_cfg), **options)
|
|
1126
|
+
self.debug_print()
|
|
1127
|
+
# TODO
|
|
1128
|
+
case "Scrollbar":
|
|
1129
|
+
ctrl = tk.Scrollbar(master.control)
|
|
1130
|
+
ctrl.configure(**options)
|
|
1131
|
+
case "Listbox":
|
|
1132
|
+
ctrl = ListboxCtrl(master, idctrl, **options)
|
|
1133
|
+
case "PicsListview":
|
|
1134
|
+
ctrl = PicsListviewCtrl(master, self, owner, idctrl,
|
|
1135
|
+
int(attr_dict["num_column"]), int(attr_dict["pic_size"]),
|
|
1136
|
+
self._res_path)
|
|
1137
|
+
case "Dialog":
|
|
1138
|
+
ctrl = DialogCtrl(self, ctrl_cfg)
|
|
1139
|
+
self.debug_print()
|
|
1140
|
+
case "Notebook":
|
|
1141
|
+
ctrl = NotebookCtrl(master, self, owner, idctrl,
|
|
1142
|
+
subctrlcfg_list=list(ctrl_cfg), level=level, **options)
|
|
1143
|
+
case _:
|
|
1144
|
+
raise ValueError(f"{tag}: unknown Control")
|
|
1145
|
+
|
|
1146
|
+
if "tooltip" in attr_dict:
|
|
1147
|
+
if tag in ["Canvas", "ScrolledText", "Spinbox", "Style", "Scrollbar"]:
|
|
1148
|
+
Hovertip(ctrl, attr_dict["tooltip"], hover_delay=500)
|
|
1149
|
+
else:
|
|
1150
|
+
Hovertip(ctrl.control, attr_dict["tooltip"], hover_delay=500)
|
|
1151
|
+
|
|
1152
|
+
self._idctrl_dict[idctrl] = ctrl
|
|
1153
|
+
|
|
1154
|
+
return idctrl, ctrl
|
|
1155
|
+
|
|
1156
|
+
@override
|
|
1157
|
+
def assemble_control(self, ctrl: Widget, attr_dict: dict[str, str],
|
|
1158
|
+
prefix: str = ""):
|
|
1159
|
+
|
|
1160
|
+
ctrl_type = type(ctrl)
|
|
1161
|
+
# pe(ctrl_type)
|
|
1162
|
+
if ctrl_type in [tk.Menu, DialogCtrl]:
|
|
1163
|
+
return
|
|
1164
|
+
elif ctrl_type in [tk.Canvas, scrolledtext.ScrolledText, tk.Spinbox, \
|
|
1165
|
+
ttk.Style, tk.Scrollbar]:
|
|
1166
|
+
widget = cast(tk.Widget, ctrl)
|
|
1167
|
+
elif ctrl_type is ScrollableFrameCtrl:
|
|
1168
|
+
widget = cast(ScrollableFrameCtrl, ctrl).outter
|
|
1169
|
+
else:
|
|
1170
|
+
widget = cast(tkControl, ctrl).control
|
|
1171
|
+
|
|
1172
|
+
if "layout" in attr_dict:
|
|
1173
|
+
if attr_dict["layout"] == "pack":
|
|
1174
|
+
widget.pack(**(literal_eval(attr_dict["pack"])))
|
|
1175
|
+
elif attr_dict["layout"] == "grid":
|
|
1176
|
+
widget.grid(**(literal_eval(attr_dict["grid"])))
|
|
1177
|
+
elif attr_dict["layout"] == "place":
|
|
1178
|
+
widget.place(**(literal_eval(attr_dict["place"])))
|
|
1179
|
+
else:
|
|
1180
|
+
self.debug_print(f"{prefix}, unknown layout of {attr_dict['layout']}")
|
|
1181
|
+
return
|
|
1182
|
+
else:
|
|
1183
|
+
# self._debug_print(f"{attr_dict['text']}: no assemble")
|
|
1184
|
+
return
|
|
1185
|
+
|
|
1186
|
+
if "childOpt" in attr_dict:
|
|
1187
|
+
for child in ctrl.control.winfo_children():
|
|
1188
|
+
child.grid_configure(**(literal_eval(attr_dict["childOpt"])))
|
|
1189
|
+
|
|
1190
|
+
self.debug_print(f"{prefix}, layout: {attr_dict['layout']}")
|
|
1191
|
+
|
|
1192
|
+
def create_menu(self, rootcfg: et.Element, **kwargs: object) -> tk.Menu:
|
|
1193
|
+
menubar = tk.Menu(self._win, **kwargs)
|
|
1194
|
+
|
|
1195
|
+
# def get_cmd(cmd_name, msg, ext_msg=""):
|
|
1196
|
+
def get_cmd(cmd_name: str, **kwargs):
|
|
1197
|
+
# return lambda: self.process_message(cmd_name, msg, ext_msg)
|
|
1198
|
+
return lambda: self.process_message(cmd_name, **kwargs)
|
|
1199
|
+
|
|
1200
|
+
# def get_cmd_e(cmd_name, msg, ext_msg=""):
|
|
1201
|
+
def get_cmd_e(cmd_name: str, **kwargs):
|
|
1202
|
+
# return lambda event: self.process_message(cmd_name, msg, ext_msg)
|
|
1203
|
+
return lambda event: self.process_message(cmd_name, **kwargs)
|
|
1204
|
+
|
|
1205
|
+
for menucfg in list(rootcfg):
|
|
1206
|
+
attr_dict = menucfg.attrib
|
|
1207
|
+
label = attr_dict["Header"]
|
|
1208
|
+
self.debug_print(f" Menu: {label}")
|
|
1209
|
+
menu = tk.Menu(menubar, tearoff=False)
|
|
1210
|
+
|
|
1211
|
+
if "options" in attr_dict:
|
|
1212
|
+
options = literal_eval(attr_dict["options"])
|
|
1213
|
+
else:
|
|
1214
|
+
options = {}
|
|
1215
|
+
|
|
1216
|
+
for submenucfg in list(menucfg):
|
|
1217
|
+
tag = submenucfg.tag
|
|
1218
|
+
subattr_dict = submenucfg.attrib
|
|
1219
|
+
if tag == "Separator":
|
|
1220
|
+
menu.add_separator()
|
|
1221
|
+
self.debug_print(f" subMenu: {submenucfg.tag}")
|
|
1222
|
+
continue
|
|
1223
|
+
if "options" in subattr_dict:
|
|
1224
|
+
sub_options = literal_eval(subattr_dict["options"])
|
|
1225
|
+
else:
|
|
1226
|
+
sub_options = {}
|
|
1227
|
+
sub_label = subattr_dict["Command"]
|
|
1228
|
+
if "id" in subattr_dict:
|
|
1229
|
+
idmenu = subattr_dict["id"]
|
|
1230
|
+
else:
|
|
1231
|
+
idmenu = str(sub_label.replace(" ", "").replace("...", ""))
|
|
1232
|
+
self.debug_print(f" subMenu: {tag} -> {sub_label}")
|
|
1233
|
+
if tag == "Checkbutton":
|
|
1234
|
+
var_name = subattr_dict["variable"]
|
|
1235
|
+
self.__dict__[f"_{var_name}"] = tk.BooleanVar()
|
|
1236
|
+
var = self.__dict__[f"_{var_name}"]
|
|
1237
|
+
# var.set(True)
|
|
1238
|
+
# msg = "Changed"
|
|
1239
|
+
# ext_msg = var.get()
|
|
1240
|
+
# cmd = get_cmd(cmd_name, msg, ext_msg)
|
|
1241
|
+
kwargs = {"event": "Changed", "val": var.get()}
|
|
1242
|
+
cmd = get_cmd(idmenu, **kwargs)
|
|
1243
|
+
menu.add_checkbutton(
|
|
1244
|
+
label=sub_label, command=cmd, variable=var, **sub_options
|
|
1245
|
+
)
|
|
1246
|
+
elif tag == "MenuItem":
|
|
1247
|
+
# msg = "Clicked"
|
|
1248
|
+
# ext_msg = ""
|
|
1249
|
+
kwargs = {"event": "Clicked"}
|
|
1250
|
+
# cmd = get_cmd(cmd_name, msg, ext_msg)
|
|
1251
|
+
cmd = get_cmd(idmenu, **kwargs)
|
|
1252
|
+
menu.add_command(label=sub_label, command=cmd, **sub_options)
|
|
1253
|
+
else:
|
|
1254
|
+
raise ValueError(f" Unknown Menu: {tag} -> {sub_label}")
|
|
1255
|
+
|
|
1256
|
+
if "accelerator" in sub_options:
|
|
1257
|
+
shortcut_lst = sub_options["accelerator"].split("+")
|
|
1258
|
+
shortcut = (
|
|
1259
|
+
"<"
|
|
1260
|
+
+ shortcut_lst[0].replace("Ctrl", "Control").strip()
|
|
1261
|
+
+ "-"
|
|
1262
|
+
+ shortcut_lst[1].lower().strip()
|
|
1263
|
+
+ ">"
|
|
1264
|
+
)
|
|
1265
|
+
# pv(shortcut)
|
|
1266
|
+
# cmd = get_cmd_e(cmd_name, msg, ext_msg)
|
|
1267
|
+
cmd = get_cmd_e(idmenu, **kwargs)
|
|
1268
|
+
self._win.bind_all(shortcut, cmd)
|
|
1269
|
+
|
|
1270
|
+
menubar.add_cascade(label=label, menu=menu, **options)
|
|
1271
|
+
|
|
1272
|
+
return menubar
|
|
1273
|
+
|
|
1274
|
+
def show_info(self, title: str = "", message: str = ""):
|
|
1275
|
+
tkMessageBox.showinfo(title, message)
|
|
1276
|
+
|
|
1277
|
+
def show_warn(self, title: str = "", message: str = ""):
|
|
1278
|
+
tkMessageBox.showwarning(title, message)
|
|
1279
|
+
|
|
1280
|
+
@override
|
|
1281
|
+
def show_err(self, title: str = "", message: str = ""):
|
|
1282
|
+
tkMessageBox.showerror(title, message)
|
|
1283
|
+
|
|
1284
|
+
def ask_yesno(self, title: str = "", message: str = ""):
|
|
1285
|
+
return tkMessageBox.askyesno(title, message)
|
|
1286
|
+
|
|
1287
|
+
"""
|
|
1288
|
+
@override
|
|
1289
|
+
def process_message(self, idmsg: str, **kwargs):
|
|
1290
|
+
if idmsg in ["Exit", "Quit"]:
|
|
1291
|
+
self.exit_window()
|
|
1292
|
+
return
|
|
1293
|
+
return MsgLoop.process_message(self, idmsg, **kwargs)
|
|
1294
|
+
"""
|
|
1295
|
+
|
|
1296
|
+
@override
|
|
1297
|
+
def go(self):
|
|
1298
|
+
self.register_eventhandler("Exit", self.exit)
|
|
1299
|
+
self.register_eventhandler("Quit", self.exit)
|
|
1300
|
+
|
|
1301
|
+
super().back(False)
|
|
1302
|
+
|
|
1303
|
+
# self._x = self._win.winfo_rootx()
|
|
1304
|
+
# self._y = self._win.winfo_rooty()
|
|
1305
|
+
|
|
1306
|
+
self._win.focus_force()
|
|
1307
|
+
# self._win.focus_set()
|
|
1308
|
+
|
|
1309
|
+
self._win.mainloop()
|
|
1310
|
+
|
|
1311
|
+
def _on_winresize(self, event: tk.Event[tk.Misc]):
|
|
1312
|
+
""" listen events of window resizing.
|
|
1313
|
+
"""
|
|
1314
|
+
if event is not None:
|
|
1315
|
+
if self._ww != self._win.winfo_width() or self._hh != self._win.winfo_height():
|
|
1316
|
+
if self._ww != self._win.winfo_width():
|
|
1317
|
+
self._ww = self._win.winfo_width()
|
|
1318
|
+
if self._hh != self._win.winfo_height():
|
|
1319
|
+
self._hh = self._win.winfo_height()
|
|
1320
|
+
self.process_message("WindowResize", w=self._ww, h=self._hh)
|
|
1321
|
+
|
|
1322
|
+
def _on_keypress(self, event: tk.Event[tk.Misc]):
|
|
1323
|
+
"""
|
|
1324
|
+
event.state
|
|
1325
|
+
0x0001 Shift. 0x0004 Control.
|
|
1326
|
+
0x0002 Caps Lock. 0x0010 Num Lock.
|
|
1327
|
+
0x0008 Left-hand Alt. 0x0080 Right-hand Alt.
|
|
1328
|
+
0x0100 Mouse button 1. 0x0200 Mouse button 2.
|
|
1329
|
+
0x0400 Mouse button 3
|
|
1330
|
+
"""
|
|
1331
|
+
state=event.state
|
|
1332
|
+
# pv(state)
|
|
1333
|
+
ctrl = (state & 0x0004) >> 2
|
|
1334
|
+
shift = state & 0x0001
|
|
1335
|
+
# alt = state & 0x0008 | state & 0x0080
|
|
1336
|
+
self.process_message("KeyPress", key=event.keysym, ctrl=ctrl, shift=shift)
|
|
1337
|
+
|
|
1338
|
+
def exit(self, **kwargs: object):
|
|
1339
|
+
res = tkMessageBox.askquestion(
|
|
1340
|
+
"Exit Application", "Do you really want to exit?"
|
|
1341
|
+
)
|
|
1342
|
+
if res == "yes":
|
|
1343
|
+
super().destroy()
|
|
1344
|
+
self._win.destroy()
|