-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathwidgets.py
More file actions
5193 lines (4721 loc) · 178 KB
/
widgets.py
File metadata and controls
5193 lines (4721 loc) · 178 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# pylint: disable=import-outside-toplevel,line-too-long,too-many-lines,too-many-arguments,too-many-positional-arguments,too-many-instance-attributes,too-many-locals
"""TkEasyGUI Widgets."""
import csv
import os
import re
import sys
import threading
import tkinter as tk
from datetime import datetime
from queue import Queue
from tkinter import font as tkinter_font
from tkinter import scrolledtext, ttk
from typing import Any, Callable, Literal, Optional, Pattern, Sequence, Union, cast
from PIL import Image as PILImage
from PIL import ImageGrab, ImageTk
from . import icon_default, utils, widgets_framescrollable
from . import locale_easy as le
from .utils import (
CursorType,
ElementJustifcation,
EventMode, # type alias
FileTypeList,
FontType,
ImageResizeType,
ListboxSelectMode,
OrientationType,
PadType,
PointType,
ProgressbarMode,
ReliefType,
TextAlign,
TextVAlign,
TkEasyError,
get_current_theme,
get_root_window,
)
from .widgets_image import get_image_tk
from .widgets_window import (
EG_WINDOW_MANAGER,
generate_element_id,
generate_element_style_key,
get_active_eg_window,
get_eg_window_count,
get_last_eg_window,
get_ttk_style,
pop_easy_window,
push_easy_window,
register_element_key,
remove_element_key,
)
# ------------------------------------------------------------------------------
# TypeAlias
# ------------------------------------------------------------------------------
WINDOW_TYPE = "Window"
ELEMENT_TYPE = "Element"
LayoutType = Sequence[Sequence["Element"]]
KeyType = Union[str, int]
# ------------------------------------------------------------------------------
# Const
# ------------------------------------------------------------------------------
WINDOW_CLOSED: str = "WINDOW_CLOSED"
WIN_CLOSED: str = "WINDOW_CLOSED"
WINDOW_TIMEOUT: str = "-TIMEOUT-"
WINDOW_THREAD_END: str = "-THREAD_END-"
TIMEOUT_KEY: str = WINDOW_TIMEOUT
WINDOW_KEY_EVENT: str = "-WINDOW_KEY_EVENT-"
WINDOW_MOUSE_EVENT: str = "-WINDOW_MOUSE_EVENT-"
WINDOW_SHOW_EVENT: str = "-WINDOW_SHOW_EVENT-"
WINDOW_RESIZE_EVENT: str = "-WINDOW_RESIZE_EVENT-"
LISTBOX_SELECT_MODE_MULTIPLE: ListboxSelectMode = "multiple"
LISTBOX_SELECT_MODE_BROWSE: ListboxSelectMode = "browse"
LISTBOX_SELECT_MODE_EXTENDED: ListboxSelectMode = "extended"
LISTBOX_SELECT_MODE_SINGLE: ListboxSelectMode = "single"
TABLE_SELECT_MODE_NONE: str = tk.NONE
TABLE_SELECT_MODE_BROWSE: str = tk.BROWSE
TABLE_SELECT_MODE_EXTENDED: str = tk.EXTENDED
EG_SWAP_EVENT_NAME: str = "--swap_event_name--"
DEFAULT_PADX = 1 if utils.is_win() else 3
FILES_DELIMITER = (
"|" if utils.is_win() else ":"
) # delimiter for multiple files, used in popup_get_file with multiple_files=True
# --- window icon ---
DEFAULT_WINDOW_ICON = icon_default.ICON
# Window.screenshot method
SCREENSHOT_MACOS_ADJUST = {
"x1": 0,
"y1": 0,
"x2": 0,
"y2": 22 + 6,
} # for macOS titlebar
# ------------------------------------------------------------------------------
# Widget wrapper
# ------------------------------------------------------------------------------
# pylint: disable=too-many-instance-attributes,too-many-public-methods
class Window:
"""Main window object in TkEasyGUI"""
# pylint: disable=too-many-arguments,too-many-positional-arguments,too-many-locals,too-many-branches,too-many-statements
def __init__(
self,
title: str,
layout: LayoutType, # set elements layout
size: Optional[tuple[int, int]] = None, # window size
resizable: bool = False,
font: Optional[FontType] = None,
modal: bool = False, # modal window
keep_on_top: bool = False, # keep on top
no_titlebar: bool = False, # hide titlebar
grab_anywhere: bool = False, # can move window by dragging anywhere
alpha_channel: float = 1.0, # window alpha channel
enable_key_events: bool = False, # enable keyboard events (post WINDOW_KEY_EVENT)
enable_show_events: bool = False, # enable window show/hide events (post WINDOW_SHOW_EVENT)
enable_mouse_events: bool = False, # enable mouse events (post WINDOW_MOUSE_EVENT)
enable_resize_events: bool = False, # enable resize events (post WINDOW_RESIZE_EVENT)
return_keyboard_events: bool = False, # enable keyboard events (for compatibility)
location: Optional[tuple[int, int]] = None, # window location
center_window: bool = True, # move window to center
row_padding: int = 2, # row padding
padding_x: int = 8, # x padding around the window
padding_y: int = 8, # y padding around the window
icon: Optional[str] = None, # window icon, specify filename
key: Optional[str] = None, # window key for enable_show_events
is_hidden: bool = False, # hidden window
element_justification: ElementJustifcation = "left", # element justification
show_scrollbar: bool = False, # show scrollbar (Experimental)
**kw,
) -> None:
"""Create a window with a layout of widgets."""
self.modal: bool = modal
# check active window
active_win: Union[tk.Toplevel, tk.Tk, None] = get_active_eg_window()
if active_win is None:
active_win = get_root_window()
self.key = key
self.title: str = title
if self.key is None:
self.key = self.title
self.window: tk.Toplevel = tk.Toplevel(master=active_win)
self.timeout: Optional[int] = None
self.timeout_key: str = WINDOW_TIMEOUT
self.timeout_id: Union[str, None] = None
self.events: Queue = Queue() # Queue[key, values]
self.key_elements: dict[KeyType, "Element"] = {}
self.last_values: dict[KeyType, Any] = {}
self.flag_alive: bool = (
True # Pressing the close button will turn this flag to False.
)
self.layout: LayoutType = layout
self._event_hooks: dict[KeyType, list[Callable]] = {}
self.font: Optional[FontType] = font
self.radio_group_dict: dict[str, tk.IntVar] = {} # [variable]
self.radio_group_dict_keys: dict[str, list[str]] = {}
self.checkbox_dict: dict[str, list[str]] = {}
self.minimized: bool = False
self.maximized: bool = False
self.is_hidden: bool = is_hidden
self._keep_on_top: bool = keep_on_top
self._no_titlebar: bool = no_titlebar
self._grab_anywhere: bool = grab_anywhere
self._grab_flag: bool = False
self._start_x: Optional[int] = None
self._start_y: Optional[int] = None
self._mouse_x: Optional[int] = None
self._mouse_y: Optional[int] = None
self.alpha_channel: float = alpha_channel
self.enable_key_events: bool = enable_key_events
self.return_keyboard_events: bool = return_keyboard_events
self.font_size_average: tuple[int, int] = (12, 10)
self.row_padding: int = row_padding
self.center_window: bool = center_window
self.padding_x: int = padding_x
self.padding_y: int = padding_y
self.show_scrollbar = show_scrollbar # (experimental)
self._icon: Optional[tk.PhotoImage] = None
self._idle_time: int = 10
self._has_last_event = True
self.element_justification = element_justification
self.need_focus_widget: Optional[tk.Widget] = None
# withdraw window
self.window.withdraw() # Set the window to hidden mode
# Icon
if icon:
self._set_icon(icon)
else:
self._set_icon(DEFAULT_WINDOW_ICON)
# Canvas
self.canvas: Optional[tk.Canvas] = None
if show_scrollbar:
self.canvas = tk.Canvas(self.window)
self.canvas.pack(
side=tk.LEFT, fill=tk.BOTH, expand=True, padx=padding_x, pady=padding_y
)
# scrollbar
self.frame_bar = tk.Scrollbar(
self.window, orient=tk.VERTICAL, command=self.canvas.yview
)
self.frame_bar.pack(side=tk.RIGHT, fill=tk.Y)
self.canvas.configure(yscrollcommand=self.frame_bar.set)
# Frame
self.frame = tk.Frame(self.canvas)
self.canvas.create_window((0, 0), window=self.frame, anchor=tk.NW)
else:
self.frame = tk.Frame(self.window)
self.frame.pack(expand=True, fill="both", padx=padding_x, pady=padding_y)
# self.frame.configure(style="TFrame")
# set window properties
self.set_title(title)
self.window.protocol("WM_DELETE_WINDOW", self._close_handler)
self.size: Union[tuple[int, int], None] = size
if size is not None:
self.set_size(size)
self.window.resizable(resizable, resizable)
# create widgets
self._create_widget(self.frame, layout)
# pack frame
self.frame.rowconfigure(0, weight=1)
if keep_on_top:
self.window.attributes("-topmost", True)
if no_titlebar:
self.window.after_idle(self.hide_titlebar, True)
if grab_anywhere:
self.set_grab_anywhere(True)
# font
if font is not None:
self._calc_font_size(font)
# set hidden
self.window.attributes("-alpha", 0) # hidden window for calculating size
# bind events
if self.enable_key_events:
self.window.bind(
"<Key>",
lambda e: self._event_handler(
WINDOW_KEY_EVENT,
{
"event": e,
"key": e.keysym,
"event_type": "key",
"window.key": self.key,
},
),
)
if self.return_keyboard_events: # for compatibility with PySimpleGUI
self.window.bind(
"<Key>",
lambda e: self._event_handler(
e.keysym if len(e.keysym) == 1 else f"{e.keysym}:{e.keycode}", {}
),
)
# push window
self.parent_window: Union[Window, None] = get_last_eg_window()
push_easy_window(self)
# set show event
if enable_show_events:
self.window.bind("<Map>", self._on_window_show)
self.window.bind("<Unmap>", self._on_window_hide)
# set mouse events
if enable_mouse_events:
self.window.bind("<Motion>", self._on_mouse_move)
self.window.bind("<Button>", self._on_mouse_click)
# set window size
self.frame.bind("<Configure>", self._on_frame_configure)
self._enable_resize_events = enable_resize_events
# position
if location is not None:
self.set_location(location)
else:
# could not get size with geometry() before window is shown
# so, move window to center after window is shown `_on_show_event`
pass
# set idle event
self.update_idle_tasks()
self.window.after_idle(self._on_show_event)
self._options = kw
def _on_mouse_move(self, event):
"""Mouse move event."""
self.post_event(WINDOW_MOUSE_EVENT, {"event": event, "event_type": "mousemove"})
def _on_mouse_click(self, event):
"""Mouse click event."""
self.post_event(WINDOW_MOUSE_EVENT, {"event": event, "event_type": "click"})
def _on_show_event(self) -> None:
"""Call this method only once on the first execution."""
# hide window for showing ghost window (#102)
alpha = self.alpha_channel
self.set_alpha_channel(0)
if self.modal:
# set modal action
self.window.attributes("-topmost", 1) # topmost
# self.window.transient(parent)
self.window.grab_set()
# show
if not self.is_hidden:
root = get_root_window()
root.update_idletasks()
root.focus_force()
self.window.deiconify()
self.window.after_idle(self.focus)
# center window
if self.center_window or self.modal:
if self.parent_window is None: # only this window
self.move_to_center()
else:
self.move_to_center(center_pos=self.parent_window.get_center_location())
# show window
self.set_alpha_channel(alpha)
def _on_window_show(self, event: Any) -> None:
values: dict[Union[str, int], Any] = self.get_values()
values["event"] = event
values["window.key"] = self.key
values["window.status"] = "show"
self.post_event(WINDOW_SHOW_EVENT, values)
def _on_window_hide(self, event: Any) -> None:
values: dict[Union[str, int], Any] = self.get_values()
values["event"] = event
values["window.key"] = self.key
values["window.status"] = "hide"
self.post_event(WINDOW_SHOW_EVENT, values)
def focus(self) -> None:
"""Focus the window."""
self.window.focus_force()
def focus_element(self, key: str) -> None:
"""Focus the element."""
elem = self.get_element_by_key(key)
if elem is not None:
elem.focus()
def post_event(self, key: KeyType, values: dict[KeyType, Any]) -> None:
"""Post an event."""
self.events.put((key, values))
def post_event_after(
self, msec: int, key: KeyType, values: dict[KeyType, Any]
) -> None:
"""Post an event after msec."""
self.window.after(msec, self.events.put, (key, values))
def set_timeout(self, callback: Callable, msec: int, *args, **kw) -> None:
"""Set a timeout event."""
self.window.after(msec, callback, *args, **kw)
def _on_frame_configure(self, event):
"""Handle frame configure event."""
if self._enable_resize_events:
self.post_event(WINDOW_RESIZE_EVENT, {"event": event})
# set scrollbar
if self.canvas is None:
return
region = self.canvas.bbox("all")
self.canvas.configure(scrollregion=region)
# set size
pre_size = self.size
w, h = region[2], region[3]
sw, sh = self.get_screen_size()
pad_x = self.padding_x * 2
pad_y = self.padding_y * 2
if pre_size is None:
if w > sw:
w = sw - pad_x
if h > sh:
h = sh - pad_y
self.set_size((w + pad_x, h + pad_y))
self.size = pre_size
def set_location(self, xy: tuple[int, int]) -> None:
"""Set window location."""
self.window.geometry(f"+{xy[0]}+{xy[1]}")
def get_location(self) -> tuple[int, int]:
"""Get window location."""
loc = self.window.geometry().split("+")
return (int(loc[1]), int(loc[2]))
def get_center_location(self) -> tuple[int, int]:
"""Get center location."""
w, h = self.get_size()
x, y = self.get_location()
return (x + w // 2, y + h // 2)
def __enter__(self):
"""Initialize resource"""
return self
def __exit__(self, exc_type, exc_value, traceback):
"""Finalize resource"""
self.close()
def register_event_hooks(self, hooks: dict[str, list[Callable]]) -> None:
"""
Register event hooks. (append hook events)
**Example**
```py
window.register_event_hooks({
"-input-": [
lambda event, values: print("1", event, values),
lambda event, values: print("2", event, values),
lambda event, values: True, # stop event propagation
lambda event, values: print("3", event, values),
],
```
**Note**
- If you specify a function that returns True, it changes the event name to f"{event}-stopped" and then re-collects the values associated with keys that occur afterwards.
- @see [Window.read](#windowread)
"""
for event_name, handle_list in hooks.items():
for handle in handle_list:
if event_name not in self._event_hooks:
self._event_hooks[event_name] = []
self._event_hooks[event_name].append(handle)
def _create_widget(
self,
parent: tk.Widget,
layout: LayoutType,
align: TextAlign = "left",
valign: TextVAlign = "top",
):
"""Create widget from layout"""
# check layout
if not (len(layout) > 0 and isinstance(layout[0], (list, tuple))):
raise TkEasyError(
f"Invalid layout, should specify a two-dimensional list: {layout}"
)
# prepare create
for widgets in layout:
for elem in widgets:
elem.prepare_create(self)
# check element_justification
layout_ej: LayoutType = []
tmp_layout: list[list[Element]] = []
if self.element_justification in ["center", "c"]:
for widgets in layout:
cells: list[Element] = []
cells.append(Push())
cells.extend(widgets)
cells.append(Push())
tmp_layout.append(cells)
elif self.element_justification in ["right", "r"]:
for widgets in layout:
cells_r: list[Element] = []
cells_r.extend(widgets)
cells_r.append(Push())
tmp_layout.append(cells_r)
else:
tmp_layout = cast(list[list[Element]], layout)
layout_ej = tmp_layout
# create widgets
self.need_focus_widget = None
for row_no, widgets in enumerate(layout_ej):
bgcolor = None
if parent is not None:
try:
bgcolor = parent.cget("background")
except tk.TclError:
pass
frame_prop = {"name": f"tkeasygui_frame_row_{row_no}"}
if bgcolor is not None:
frame_prop["background"] = bgcolor
frame_row = tk.Frame(parent, **frame_prop) # type: ignore
# columns
prev_element: Union[Element, None] = None
row_pack_prop: dict[str, Any] = {
"expand": False,
"fill": "x",
"side": valign,
"pady": self.row_padding,
}
# reversed?
if align == "right":
widgets = reversed(widgets) # type: ignore
for col_no, elemment in enumerate(widgets):
# create widget
elem = elemment
# set window and parent
elem.window = self
elem.parent = frame_row
elem.col_no = col_no
elem.row_no = row_no
# set prev_element and next_element
elem.prev_element = prev_element # set prev_element
if prev_element is not None:
prev_element.next_element = elem
prev_element = elem
# create widget
try:
elem_parent: Any = frame_row
if isinstance(parent, ttk.Notebook):
elem_parent = parent
widget: Any = elem.create(self, elem_parent)
widget.tkeasygui_elem = elem
except Exception as e:
print(e.__traceback__, file=sys.stderr)
raise TkEasyError(
f"Window._create_widget.Failed `{elem.element_type}` key=`{elem.get_name()}` {elem.props} reason:{e}"
) from e
# check key
if elem.has_value or (elem.key is not None):
self.key_elements[elem.key] = elem
# check focus widget
if elem.has_value and (self.need_focus_widget is None):
self.need_focus_widget = widget
# check specila key
if (self.need_focus_widget is None) and (elem.key in ("OK", "Yes")):
self.need_focus_widget = widget
# create sub widgets
try:
# has children?
if elem.has_children:
parent_widget = widget
if elem.container_parent is not None:
parent_widget = elem.container_parent
self._create_widget(
parent_widget,
elem.layout,
align=elem.text_align,
valign=elem.vertical_alignment,
)
except tk.TclError as e:
print(e.__traceback__, file=sys.stderr)
raise TkEasyError(
f"Window._create_widget.Failed(children) `{elem.element_type}` key=`{elem.key}` {elem.props} reason:{e}"
) from e
# post create
elem.post_create(self, frame_row)
# bind event (before create)
bind_dict = elem.get_bind_dict()
for event_name, handle_t in bind_dict.items():
self.bind(elem, event_name, handle_t[0], handle_t[1], handle_t[2])
# menu ?
if isinstance(elem, Menu):
continue
# Tab?
if isinstance(parent, ttk.Notebook):
# print("@@@@ TabGroup", type(parent), type(elem.widget), elem.get())
parent.add(elem.widget, text=elem.get()) # type: ignore
if isinstance(elem, Tab):
group: TabGroup = parent.tkeasygui_elem # type: ignore
tab: Tab = elem
tab.rows = max(tab.rows, group.max_rows)
tab.cols = max(tab.cols, group.max_cols)
continue
# pack widget
fill_props = elem.get_pack_props(align, valign)
widget.pack(**fill_props)
# expand_y?
if elem.expand_y:
row_pack_prop["expand"] = True
row_pack_prop["fill"] = "both"
# pady
if elem.pady is not None:
row_pack_prop["pady"] = elem.pady
# add row
frame_row.pack(**row_pack_prop)
# end of create
if self.need_focus_widget is not None:
self.need_focus_widget.focus_set()
def _calc_font_size(self, font: FontType) -> None:
"""Calculate font size."""
font_obj = tkinter_font.Font()
if font is not None:
if len(font) >= 2:
font_obj = tkinter_font.Font(family=font[0], size=font[1])
elif len(font) == 1:
font_obj = tkinter_font.Font(family=font[0])
# calc measure
# The letter 'M' is commonly used to represent the average width of a font in typography. This is because the 'M' is relatively wide, making it suitable for indicating width in comparison to other characters, especially in fixed-width (monospace) fonts.
m_size = font_obj.measure("M")
s_size = font_obj.measure("s")
a_size = font_obj.measure("A")
w = (m_size + s_size + a_size) // 3
h = font_obj.metrics("linespace")
self.font_size_average = (w, h)
def move(self, x: int, y: int) -> None:
"""Move the window. (same as set_location)"""
self.set_location((x, y))
def get_screen_size(self) -> tuple[int, int]:
"""Get the screen size."""
return utils.get_screen_size()
def update_idle_tasks(self) -> None:
"""Update idle tasks."""
self.window.update_idletasks()
def move_to_center(self, center_pos: Union[tuple[int, int], None] = None) -> None:
"""Move the window to the center of the screen."""
if center_pos is None:
w, h = self.get_screen_size()
cx, cy = w // 2, h // 2
else:
cx, cy = center_pos
try:
if self.size is None:
win_x, win_y = self.get_size()
if win_x < 10 or win_y < 10:
win_x = 600 # 適当なサイズ
win_y = 400
else:
win_x, win_y = self.size
x = cx - win_x // 2
y = cy - win_y // 2
# It will be out of range, so move it to the center.
if x < 0 or y < 0:
w, h = self.get_screen_size()
cx, cy = w // 2, h // 2
x = cx - win_x // 2
y = cy - win_y // 2
self.move(x, y)
except (ZeroDivisionError, TypeError) as _:
pass
def get_size(self) -> tuple[int, int]:
"""Get the window size."""
size = self.window.geometry().split("+")[0].split("x")
return (int(size[0]), int(size[1]))
def get_element_by_key(self, key: str) -> Union["Element", None]:
"""Get an element by its key."""
return self.key_elements[key] if key in self.key_elements else None
def get_elements_by_type(self, element_type: str) -> list["Element"]:
"""Get elements by type."""
result: list["Element"] = []
for rows in self.layout:
for elem in rows:
if elem.element_type.lower() == element_type.lower():
result.append(elem)
return result
def read(
self, timeout: Union[int, None] = None, timeout_key: str = WINDOW_TIMEOUT
) -> tuple[KeyType, dict[KeyType, Any]]:
"""Read events from the window."""
self.timeout = timeout
self.timeout_key = timeout_key
timeout_chcker_id = time_checker_start()
# get root window
root = get_root_window()
# update window before mainloop
root.update()
# set focus timer (once when window show)
if self.need_focus_widget is not None:
self.window.after_idle(self._check_focus_widget)
# mainloop for hook
key: KeyType = ""
values: dict[KeyType, Any] = {} # set default key and values
# mainloop - read a event
while True:
# set timeout
if self.timeout_id is not None:
self.window.after_cancel(self.timeout_id)
self.window.update_idletasks()
self.window.update()
# set next event
if self._has_last_event:
self.timeout_id = self.window.after_idle(self._window_idle_handler)
else:
self.timeout_id = self.window.after(
self._idle_time, self._window_idle_handler
)
# -----------------------------------------------------
# mainloop - should be called only once
# -----------------------------------------------------
root.mainloop()
# -----------------------------------------------------
# after mainloop, check events
# -----------------------------------------------------
# timeout ?
if timeout is not None:
# check interval
interval = time_checker_end(timeout_chcker_id)
if interval > timeout:
self._has_last_event = True
key, values = (self.timeout_key, {}) # create timeout event
return (key, values)
# get ui event
if self.events.empty():
self._has_last_event = False
continue
self._has_last_event = True
key, values = self.events.get()
# _event_hooks
if key in self._event_hooks:
flag_stop = self._dispatch_event_hooks(key, values)
if flag_stop:
key = f"{key}-stopped" # change event name
values = self.get_values() # collect values again
# If an event hidden from the user occurs, continue to use the mainloop.
if isinstance(key, str) and key.endswith("/hide"):
continue # hide system events
# return a event
break
return (key, values)
def _check_focus_widget(self) -> None:
"""Check Focus window"""
if not self.flag_alive:
return
if self.need_focus_widget is not None:
self.need_focus_widget.focus_set()
self.need_focus_widget = None
_exit_mainloop()
def start_thread(
self,
target: Callable,
*args,
end_key: str = WINDOW_THREAD_END, # the thread processing is complete, end_key will be released
**kw,
) -> None:
"""
Start a thread.
### Example
```py
import TkEasyGUI as eg
# long-running process sample
def long_running_process(wait):
print("sleep start")
time.sleep(wait)
return f"done {wait}"
# create a window
with eg.Window("threading", layout=[[eg.Button("Run")]]) as window:
# event loop
for event, values in window.event_iter():
if event == "Run":
window.start_thread(long_running_process, end_key="-threadend-", wait=3)
if event == "-threadend-":
result = values["-threadend-"]
eg.print("Thread end", result)
```
"""
# target should be callable
def _thread_target():
try:
result = target(*args, **kw)
self._event_handler(end_key, {"result": True, end_key: result})
except Exception as e: # pylint: disable=broad-except
print(f"Window.start_thread.error: {e}", file=sys.stderr)
self._event_handler(end_key, {"result": False, "error": e})
# start thread
threading.Thread(target=_thread_target).start()
def event_iter(
self, timeout: Union[int, None] = None, timeout_key: str = TIMEOUT_KEY
) -> Any:
"""
Return generator with event and values
**Example**
```py
import TkEasyGUI as eg
# create a window
with eg.Window("test", layout=[[eg.Button("Hello")]]) as window:
# event loop
for event, values in window.event_iter():
if event == "Hello":
eg.popup("Hello, World!")
```
"""
# event loop
while self.is_alive():
event, values = self.read(timeout=timeout, timeout_key=timeout_key)
yield (event, values)
def _dispatch_event_hooks(self, key: KeyType, values: dict[KeyType, Any]) -> bool:
"""Dispatch event hooks."""
# execute _event_hooks
flag_stop = False
if key in self._event_hooks:
for handle in self._event_hooks[key]:
result = handle(key, values)
if result is True:
flag_stop = True
break
return flag_stop
def set_size(self, size: tuple[int, int]) -> None:
"""Set the window size."""
self.window.geometry(f"{size[0]}x{size[1]}")
self.size = size
def set_title(self, title: str) -> None:
"""Set the title of the window."""
self.window.title(title)
self.title = title
def minimize(self) -> None:
"""Minimize the window."""
self.window.iconify()
self.minimized = True
def normal(self) -> None:
"""Set normal window."""
if self.minimized:
self.window.deiconify()
self.minimized = False
if self.maximized:
self.window.state("normal")
self.maximized = False
def hide(self) -> None:
"""Hide the window."""
self.window.withdraw()
self.is_hidden = True
def un_hide(self) -> None:
"""Un hide the window."""
if self.is_hidden:
self.window.deiconify()
self.is_hidden = False
def maximize(self) -> None:
"""Maximize the window. (`resizable` should be set to True)"""
self.window.state("zoomed")
self.maximized = True
def set_alpha_channel(self, alpha: float) -> None:
"""Set the alpha channel of the window."""
self.window.attributes("-alpha", alpha)
self.alpha_channel = alpha
def get_values(self) -> dict[KeyType, Any]:
"""Get values from the window."""
values: dict[KeyType, Any] = {}
for key, val in self.key_elements.items():
if not val.has_value:
continue
# get value from widget if possible
try:
values[key] = val.get()
except Exception: # pylint: disable=broad-except
# if not possible, return last_values
return self.last_values
# add radio group
for group, vals in self.radio_group_dict.items():
selected = vals.get()
values[group] = (
self.radio_group_dict_keys[group][selected - 1] if selected > 0 else ""
)
# add checkbox group
for group, check_keys in self.checkbox_dict.items():
selected_keys = []
for key in check_keys:
if values[key]:
selected_keys.append(key)
values[group] = selected_keys
# set cache
self.last_values = values
return values
def _window_idle_handler(self) -> None:
"""Handle window idle event."""
_exit_mainloop()
def dispatch_event(
self,
key: Union[str, int],
values: Union[dict[Union[str, int], Any], None] = None,
) -> None:
"""
Dispatch an event to the window.
**Example**
```py
window.dispatch_event("hoge", {"name": "World"})
```
"""
# set value
if values is None:
values = {}
for k, v in self.get_values().items():
values[k] = v
# check EG_SWAP_EVENT_NAME
if EG_SWAP_EVENT_NAME in values:
key = values.pop(EG_SWAP_EVENT_NAME)
# put event
self.events.put((key, values))
_exit_mainloop()
def _event_handler(
self, key: Union[str, int], values: Union[dict[Union[str, int], Any], None]
) -> None:
"""Handle an event."""
self.dispatch_event(key, values)
def _exit_main_loop(self) -> None:
"""Exit mainloop"""
if self.timeout_id is not None:
self.window.after_cancel(self.timeout_id)
_exit_mainloop()
def _close_handler(self):
"""Handle a window close event."""
self.flag_alive = False
if self.timeout_id is not None:
self.window.after_cancel(self.timeout_id)
self._event_handler(WINDOW_CLOSED, None)
def keep_on_top(self, flag: bool) -> None:
"""Set the window to keep on top."""
self.window.attributes("-topmost", flag)
self._keep_on_top = flag
def send_to_back(self) -> None:
"""Send the window to the back, and make it not keep on top."""
self.window.attributes("-topmost", False)
self._keep_on_top = False
self.window.lower()
def hide_titlebar(self, flag: bool) -> None:
"""Hide the titlebar."""
try:
self.window.overrideredirect(flag)
self._no_titlebar = flag
except tk.TclError:
pass
def close(self) -> None:
"""Close the window."""
# The phenomenon where a closed window remains visible is occurring, so forcibly making it transparent.
try:
self.window.grab_release()
except tk.TclError as _:
pass
try:
self.set_alpha_channel(0.0) # force hide
except tk.TclError as _:
pass
try:
self.hide()
except tk.TclError as _:
pass
# already closed?
if not self.flag_alive:
return
root = get_root_window()
# remove from key registry
for key in self.key_elements:
remove_element_key(key)
# close window
try:
self.flag_alive = False
# update window
try:
root.update()
except tk.TclError as _:
pass
# destroy window in TKinter
try:
self.window.destroy() # close window
except tk.TclError: # ignore
pass
# update window again
try:
root.update()
except tk.TclError:
pass
# remove from TkEasyGUI window stack
try:
pop_easy_window(self)
except tk.TclError: # ignore
pass
# activate parent window
try:
if self.parent_window is not None:
self.parent_window.window.focus_force()
except tk.TclError: # ignore
pass
# check window count
win_count = get_eg_window_count()
if win_count == 0:
self.window.quit() # quit app
### print("TkEasyGUI.Window.close: window closed")
except tk.TclError as e:
print(f"Window.close.failed: {e}", file=sys.stderr)