Debian Codegraph @

tksheet/sheet.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import tkinter as tk
4 from bisect import bisect_left
5 from collections import deque
6 from collections.abc import Callable, Generator, Hashable, Iterator, Sequence
7 from contextlib import suppress
8 from functools import partial
9 from itertools import accumulate, chain, filterfalse, islice, product, repeat
10 from operator import attrgetter
11 from re import IGNORECASE, escape, sub
12 from timeit import default_timer
13 from tkinter import ttk
14 from typing import Any, Literal
15
16 from .column_headers import ColumnHeaders
17 from .constants import (
18 ALL_BINDINGS,
19 BINDING_TO_ATTR,
20 MODIFIED_BINDINGS,
21 SELECT_BINDINGS,
22 USER_OS,
23 align_value_error,
24 backwards_compatibility_keys,
25 emitted_events,
26 named_span_types,
27 rc_binding,
28 scrollbar_options_keys,
29 )
30 from .find_window import replacer
31 from .functions import (
32 add_highlight,
33 add_to_options,
34 alpha2idx,
35 bisect_in,
36 box_gen_coords,
37 consecutive_ranges,
38 convert_align,
39 del_from_options,
40 del_named_span_options,
41 del_named_span_options_nested,
42 dropdown_search_function,
43 event_dict,
44 fix_format_kwargs,
45 force_bool,
46 get_checkbox_dict,
47 get_checkbox_kwargs,
48 get_dropdown_dict,
49 get_dropdown_kwargs,
50 idx_param_to_int,
51 is_iterable,
52 key_to_span,
53 mod_event_val,
54 new_tk_event,
55 num2alpha,
56 pop_positions,
57 set_align,
58 set_readonly,
59 span_froms,
60 span_ranges,
61 stored_event_dict,
62 tksheet_type_error,
63 try_binding,
64 unpack,
65 )
66 from .main_table import MainTable
67 from .other_classes import (
68 Box_nt,
69 DotDict,
70 EventDataDict,
71 FontTuple,
72 GeneratedMouseEvent,
73 Node,
74 ProgressBar,
75 Selected,
76 SelectionBox,
77 Span,
78 )
79 from .row_index import RowIndex
80 from .sheet_options import new_sheet_options
81 from .sorting import fast_sort_key, natural_sort_key, version_sort_key # noqa: F401
82 from .themes import (
83 theme_black,
84 theme_dark,
85 theme_dark_blue,
86 theme_dark_green,
87 theme_light_blue,
88 theme_light_green,
89 )
90 from .tksheet_types import Binding, CellPropertyKey, CreateSpanTypes, ExtraBinding
91 from .top_left_rectangle import TopLeftRectangle
92
93
94 class Sheet(tk.Frame):
95 def __init__(
96 self,
97 parent: tk.Misc,
98 name: str = "!sheet",
99 show_table: bool = True,
100 show_top_left: bool | None = None,
101 show_row_index: bool = True,
102 show_header: bool = True,
103 show_x_scrollbar: bool = True,
104 show_y_scrollbar: bool = True,
105 width: int | None = None,
106 height: int | None = None,
107 headers: None | list[Any] = None,
108 header: None | list[Any] = None,
109 row_index: None | list[Any] = None,
110 index: None | list[Any] = None,
111 default_header: Literal["letters", "numbers", "both"] | None = "letters",
112 default_row_index: Literal["letters", "numbers", "both"] | None = "numbers",
113 data_reference: None | Sequence[Sequence[Any]] = None,
114 data: None | Sequence[Sequence[Any]] = None,
115 # either (start row, end row, "rows"), (start column, end column, "rows") or
116 # (cells start row, cells start column, cells end row, cells end column, "cells") # noqa: E501
117 startup_select: tuple[int, int, str] | tuple[int, int, int, int, str] = None,
118 startup_focus: bool = True,
119 total_columns: int | None = None,
120 total_rows: int | None = None,
121 default_column_width: int = 120,
122 default_header_height: str | int = "1",
123 default_row_index_width: int = 70,
124 default_row_height: str | int = "1",
125 min_column_width: int = 1,
126 max_column_width: float = float("inf"),
127 max_row_height: float = float("inf"),
128 max_header_height: float = float("inf"),
129 max_index_width: float = float("inf"),
130 after_redraw_time_ms: int = 16,
131 set_all_heights_and_widths: bool = False,
132 zoom: int = 100,
133 align: str = "nw",
134 header_align: str = "n",
135 row_index_align: str | None = None,
136 index_align: str = "n",
137 displayed_columns: list[int] | None = None,
138 all_columns_displayed: bool = True,
139 displayed_rows: list[int] | None = None,
140 all_rows_displayed: bool = True,
141 to_clipboard_delimiter: str = "\t",
142 to_clipboard_quotechar: str = '"',
143 to_clipboard_lineterminator: str = "\n",
144 from_clipboard_delimiters: list[str] | str = "\t",
145 show_default_header_for_empty: bool = True,
146 show_default_index_for_empty: bool = True,
147 page_up_down_select_row: bool = True,
148 paste_can_expand_x: bool = False,
149 paste_can_expand_y: bool = False,
150 paste_insert_column_limit: int | None = None,
151 paste_insert_row_limit: int | None = None,
152 show_dropdown_borders: bool = False,
153 arrow_key_down_right_scroll_page: bool = False,
154 cell_auto_resize_enabled: bool = True,
155 auto_resize_row_index: bool | Literal["empty"] = "empty",
156 auto_resize_columns: int | None = None,
157 auto_resize_rows: int | None = None,
158 set_cell_sizes_on_zoom: bool = False,
159 font: tuple[str, int, str] = FontTuple(
160 "Calibri",
161 13 if USER_OS == "darwin" else 11,
162 "normal",
163 ),
164 header_font: tuple[str, int, str] = FontTuple(
165 "Calibri",
166 13 if USER_OS == "darwin" else 11,
167 "normal",
168 ),
169 index_font: tuple[str, int, str] = FontTuple(
170 "Calibri",
171 13 if USER_OS == "darwin" else 11,
172 "normal",
173 ), # currently has no effect
174 popup_menu_font: tuple[str, int, str] = FontTuple(
175 "Calibri",
176 13 if USER_OS == "darwin" else 11,
177 "normal",
178 ),
179 max_undos: int = 30,
180 column_drag_and_drop_perform: bool = True,
181 row_drag_and_drop_perform: bool = True,
182 empty_horizontal: int = 50,
183 empty_vertical: int = 50,
184 selected_rows_to_end_of_window: bool = False,
185 horizontal_grid_to_end_of_window: bool = False,
186 vertical_grid_to_end_of_window: bool = False,
187 show_vertical_grid: bool = True,
188 show_horizontal_grid: bool = True,
189 display_selected_fg_over_highlights: bool = False,
190 show_selected_cells_border: bool = True,
191 edit_cell_tab: Literal["right", "down", ""] = "right",
192 edit_cell_return: Literal["right", "down", ""] = "down",
193 editor_del_key: Literal["forward", "backward", ""] = "forward",
194 treeview: bool = False,
195 treeview_indent: str | int = "2",
196 rounded_boxes: bool = True,
197 alternate_color: str = "",
198 allow_cell_overflow: bool = False,
199 # "" no wrap, "w" word wrap, "c" char wrap
200 table_wrap: Literal["", "w", "c"] = "c",
201 index_wrap: Literal["", "w", "c"] = "c",
202 header_wrap: Literal["", "w", "c"] = "c",
203 sort_key: Callable = natural_sort_key,
204 # colors
205 outline_thickness: int = 0,
206 theme: str = "light blue",
207 outline_color: str = theme_light_blue["outline_color"],
208 frame_bg: str = theme_light_blue["table_bg"],
209 popup_menu_fg: str = theme_light_blue["popup_menu_fg"],
210 popup_menu_bg: str = theme_light_blue["popup_menu_bg"],
211 popup_menu_highlight_bg: str = theme_light_blue["popup_menu_highlight_bg"],
212 popup_menu_highlight_fg: str = theme_light_blue["popup_menu_highlight_fg"],
213 table_grid_fg: str = theme_light_blue["table_grid_fg"],
214 table_bg: str = theme_light_blue["table_bg"],
215 table_fg: str = theme_light_blue["table_fg"],
216 table_editor_bg: str = theme_light_blue["table_editor_bg"],
217 table_editor_fg: str = theme_light_blue["table_editor_fg"],
218 table_editor_select_bg: str = theme_light_blue["table_editor_select_bg"],
219 table_editor_select_fg: str = theme_light_blue["table_editor_select_fg"],
220 table_selected_box_cells_fg: str = theme_light_blue["table_selected_box_cells_fg"],
221 table_selected_box_rows_fg: str = theme_light_blue["table_selected_box_rows_fg"],
222 table_selected_box_columns_fg: str = theme_light_blue["table_selected_box_columns_fg"],
223 table_selected_cells_border_fg: str = theme_light_blue["table_selected_cells_border_fg"],
224 table_selected_cells_bg: str = theme_light_blue["table_selected_cells_bg"],
225 table_selected_cells_fg: str = theme_light_blue["table_selected_cells_fg"],
226 table_selected_rows_border_fg: str = theme_light_blue["table_selected_rows_border_fg"],
227 table_selected_rows_bg: str = theme_light_blue["table_selected_rows_bg"],
228 table_selected_rows_fg: str = theme_light_blue["table_selected_rows_fg"],
229 table_selected_columns_border_fg: str = theme_light_blue["table_selected_columns_border_fg"],
230 table_selected_columns_bg: str = theme_light_blue["table_selected_columns_bg"],
231 table_selected_columns_fg: str = theme_light_blue["table_selected_columns_fg"],
232 resizing_line_fg: str = theme_light_blue["resizing_line_fg"],
233 drag_and_drop_bg: str = theme_light_blue["drag_and_drop_bg"],
234 index_bg: str = theme_light_blue["index_bg"],
235 index_border_fg: str = theme_light_blue["index_border_fg"],
236 index_grid_fg: str = theme_light_blue["index_grid_fg"],
237 index_fg: str = theme_light_blue["index_fg"],
238 index_editor_bg: str = theme_light_blue["index_editor_bg"],
239 index_editor_fg: str = theme_light_blue["index_editor_fg"],
240 index_editor_select_bg: str = theme_light_blue["index_editor_select_bg"],
241 index_editor_select_fg: str = theme_light_blue["index_editor_select_fg"],
242 index_selected_cells_bg: str = theme_light_blue["index_selected_cells_bg"],
243 index_selected_cells_fg: str = theme_light_blue["index_selected_cells_fg"],
244 index_selected_rows_bg: str = theme_light_blue["index_selected_rows_bg"],
245 index_selected_rows_fg: str = theme_light_blue["index_selected_rows_fg"],
246 index_hidden_rows_expander_bg: str = theme_light_blue["index_hidden_rows_expander_bg"],
247 header_bg: str = theme_light_blue["header_bg"],
248 header_border_fg: str = theme_light_blue["header_border_fg"],
249 header_grid_fg: str = theme_light_blue["header_grid_fg"],
250 header_fg: str = theme_light_blue["header_fg"],
251 header_editor_bg: str = theme_light_blue["header_editor_bg"],
252 header_editor_fg: str = theme_light_blue["header_editor_fg"],
253 header_editor_select_bg: str = theme_light_blue["header_editor_select_bg"],
254 header_editor_select_fg: str = theme_light_blue["header_editor_select_fg"],
255 header_selected_cells_bg: str = theme_light_blue["header_selected_cells_bg"],
256 header_selected_cells_fg: str = theme_light_blue["header_selected_cells_fg"],
257 header_selected_columns_bg: str = theme_light_blue["header_selected_columns_bg"],
258 header_selected_columns_fg: str = theme_light_blue["header_selected_columns_fg"],
259 header_hidden_columns_expander_bg: str = theme_light_blue["header_hidden_columns_expander_bg"],
260 top_left_bg: str = theme_light_blue["top_left_bg"],
261 top_left_fg: str = theme_light_blue["top_left_fg"],
262 top_left_fg_highlight: str = theme_light_blue["top_left_fg_highlight"],
263 vertical_scroll_background: str = theme_light_blue["vertical_scroll_background"],
264 horizontal_scroll_background: str = theme_light_blue["horizontal_scroll_background"],
265 vertical_scroll_troughcolor: str = theme_light_blue["vertical_scroll_troughcolor"],
266 horizontal_scroll_troughcolor: str = theme_light_blue["horizontal_scroll_troughcolor"],
267 vertical_scroll_lightcolor: str = theme_light_blue["vertical_scroll_lightcolor"],
268 horizontal_scroll_lightcolor: str = theme_light_blue["horizontal_scroll_lightcolor"],
269 vertical_scroll_darkcolor: str = theme_light_blue["vertical_scroll_darkcolor"],
270 horizontal_scroll_darkcolor: str = theme_light_blue["horizontal_scroll_darkcolor"],
271 vertical_scroll_relief: str = theme_light_blue["vertical_scroll_relief"],
272 horizontal_scroll_relief: str = theme_light_blue["horizontal_scroll_relief"],
273 vertical_scroll_troughrelief: str = theme_light_blue["vertical_scroll_troughrelief"],
274 horizontal_scroll_troughrelief: str = theme_light_blue["horizontal_scroll_troughrelief"],
275 vertical_scroll_bordercolor: str = theme_light_blue["vertical_scroll_bordercolor"],
276 horizontal_scroll_bordercolor: str = theme_light_blue["horizontal_scroll_bordercolor"],
277 vertical_scroll_active_bg: str = theme_light_blue["vertical_scroll_active_bg"],
278 horizontal_scroll_active_bg: str = theme_light_blue["horizontal_scroll_active_bg"],
279 vertical_scroll_not_active_bg: str = theme_light_blue["vertical_scroll_not_active_bg"],
280 horizontal_scroll_not_active_bg: str = theme_light_blue["horizontal_scroll_not_active_bg"],
281 vertical_scroll_pressed_bg: str = theme_light_blue["vertical_scroll_pressed_bg"],
282 horizontal_scroll_pressed_bg: str = theme_light_blue["horizontal_scroll_pressed_bg"],
283 vertical_scroll_active_fg: str = theme_light_blue["vertical_scroll_active_fg"],
284 horizontal_scroll_active_fg: str = theme_light_blue["horizontal_scroll_active_fg"],
285 vertical_scroll_not_active_fg: str = theme_light_blue["vertical_scroll_not_active_fg"],
286 horizontal_scroll_not_active_fg: str = theme_light_blue["horizontal_scroll_not_active_fg"],
287 vertical_scroll_pressed_fg: str = theme_light_blue["vertical_scroll_pressed_fg"],
288 horizontal_scroll_pressed_fg: str = theme_light_blue["horizontal_scroll_pressed_fg"],
289 vertical_scroll_borderwidth: int = 1,
290 horizontal_scroll_borderwidth: int = 1,
291 vertical_scroll_gripcount: int = 0,
292 horizontal_scroll_gripcount: int = 0,
293 scrollbar_theme_inheritance: str = "default",
294 scrollbar_show_arrows: bool = True,
295 # changing the arrowsize (width) of the scrollbars
296 # is not working with 'default' theme
297 # use 'clam' theme instead if you want to change the width
298 vertical_scroll_arrowsize: str | int = "",
299 horizontal_scroll_arrowsize: str | int = "",
300 # backwards compatibility
301 column_width: int | None = None,
302 header_height: str | int | None = None,
303 row_height: str | int | None = None,
304 row_index_width: int | None = None,
305 expand_sheet_if_paste_too_big: bool | None = None,
306 **kwargs,
307 ) -> None:
308 super().__init__(
309 parent,
310 background=frame_bg,
311 highlightthickness=outline_thickness,
312 highlightbackground=outline_color,
313 highlightcolor=outline_color,
314 )
315 self._startup_complete = False
316 self.ops = new_sheet_options()
317 if column_width is not None:
318 default_column_width = column_width
319 if header_height is not None:
320 default_header_height = header_height
321 if row_height is not None:
322 default_row_height = row_height
323 if row_index_width is not None:
324 default_row_index_width = row_index_width
325 if expand_sheet_if_paste_too_big is not None:
326 paste_can_expand_x = expand_sheet_if_paste_too_big
327 paste_can_expand_y = expand_sheet_if_paste_too_big
328 if treeview:
329 index_align = "w"
330 auto_resize_row_index = True
331 for k, v in locals().items():
332 if (xk := backwards_compatibility_keys.get(k, k)) in self.ops and v != self.ops[xk]:
333 self.ops[xk] = v
334 self.ops.from_clipboard_delimiters = (
335 from_clipboard_delimiters
336 if isinstance(from_clipboard_delimiters, str)
337 else "".join(from_clipboard_delimiters)
338 )
339 self.PAR = parent
340 self.name = name
341 self.last_event_data = EventDataDict()
342 self.bound_events = DotDict({k: [] for k in emitted_events})
343 self._dropdown_cls = Dropdown
344 self.after_redraw_id = None
345 self.after_redraw_time_ms = after_redraw_time_ms
346 self.named_span_id = 0
347 if width is not None or height is not None:
348 self.grid_propagate(0)
349 if width is not None:
350 self.config(width=width)
351 if height is not None:
352 self.config(height=height)
353 if width is not None and height is None:
354 self.config(height=300)
355 if height is not None and width is None:
356 self.config(width=350)
357 self.grid_columnconfigure(1, weight=1)
358 self.grid_rowconfigure(1, weight=1)
359 self.RI: RowIndex = RowIndex(
360 parent=self,
361 row_index_align=(
362 convert_align(row_index_align) if row_index_align is not None else convert_align(index_align)
363 ),
364 )
365 self.CH: ColumnHeaders = ColumnHeaders(
366 parent=self,
367 header_align=convert_align(header_align),
368 )
369 self.MT: MainTable = MainTable(
370 parent=self,
371 column_headers_canvas=self.CH,
372 row_index_canvas=self.RI,
373 show_index=show_row_index,
374 show_header=show_header,
375 headers=headers,
376 header=header,
377 data_reference=data if data_reference is None else data_reference,
378 total_cols=total_columns,
379 total_rows=total_rows,
380 row_index=row_index,
381 index=index,
382 zoom=zoom,
383 align=convert_align(align),
384 displayed_columns=displayed_columns,
385 all_columns_displayed=all_columns_displayed,
386 displayed_rows=displayed_rows,
387 all_rows_displayed=all_rows_displayed,
388 )
389 self.TL: TopLeftRectangle = TopLeftRectangle(
390 parent=self,
391 main_canvas=self.MT,
392 row_index_canvas=self.RI,
393 header_canvas=self.CH,
394 )
395 self.unique_id = f"{default_timer()}{self.winfo_id()}".replace(".", "")
396 style = ttk.Style()
397 for orientation in ("Vertical", "Horizontal"):
398 style.element_create(
399 f"Sheet{self.unique_id}.{orientation}.TScrollbar.trough",
400 "from",
401 scrollbar_theme_inheritance,
402 )
403 style.element_create(
404 f"Sheet{self.unique_id}.{orientation}.TScrollbar.thumb",
405 "from",
406 scrollbar_theme_inheritance,
407 )
408 style.element_create(
409 f"Sheet{self.unique_id}.{orientation}.TScrollbar.grip",
410 "from",
411 scrollbar_theme_inheritance,
412 )
413 if not scrollbar_show_arrows:
414 style.layout(
415 f"Sheet{self.unique_id}.{orientation}.TScrollbar",
416 [
417 (
418 f"Sheet{self.unique_id}.{orientation}.TScrollbar.trough",
419 {
420 "children": [
421 (
422 f"Sheet{self.unique_id}.{orientation}.TScrollbar.thumb",
423 {
424 "unit": "1",
425 "children": [
426 (
427 f"Sheet{self.unique_id}.{orientation}.TScrollbar.grip",
428 {"sticky": ""},
429 )
430 ],
431 "sticky": "nswe",
432 },
433 )
434 ],
435 "sticky": "ns" if orientation == "Vertical" else "ew",
436 },
437 )
438 ],
439 )
440 self.set_scrollbar_options()
441 self.yscroll = ttk.Scrollbar(
442 self,
443 command=self.MT._yscrollbar,
444 orient="vertical",
445 style=f"Sheet{self.unique_id}.Vertical.TScrollbar",
446 )
447 self.MT["yscrollcommand"] = self.yscroll.set
448 self.RI["yscrollcommand"] = self.yscroll.set
449 self.xscroll = ttk.Scrollbar(
450 self,
451 command=self.MT._xscrollbar,
452 orient="horizontal",
453 style=f"Sheet{self.unique_id}.Horizontal.TScrollbar",
454 )
455 self.MT["xscrollcommand"] = self.xscroll.set
456 self.CH["xscrollcommand"] = self.xscroll.set
457 self.show()
458 if show_top_left is False or (show_top_left is None and (not show_row_index or not show_header)):
459 self.hide("top_left")
460 if not show_row_index:
461 self.hide("row_index")
462 if not show_header:
463 self.hide("header")
464 if not show_table:
465 self.hide("table")
466 if not show_x_scrollbar:
467 self.hide("x_scrollbar")
468 if not show_y_scrollbar:
469 self.hide("y_scrollbar")
470 self.update_idletasks()
471 self.MT.update_idletasks()
472 self.RI.update_idletasks()
473 self.CH.update_idletasks()
474 if theme != "light blue":
475 self.change_theme(theme)
476 for k, v in locals().items():
477 if k in theme_light_blue and v != theme_light_blue[k]:
478 self.set_options(**{k: v})
479 if set_all_heights_and_widths:
480 self.set_all_cell_sizes_to_text()
481 if startup_select is not None:
482 try:
483 if startup_select[-1] == "cells":
484 self.MT.create_selection_box(*startup_select)
485 self.see(startup_select[0], startup_select[1])
486 elif startup_select[-1] == "rows":
487 self.MT.create_selection_box(
488 startup_select[0],
489 0,
490 startup_select[1],
491 len(self.MT.col_positions) - 1,
492 "rows",
493 )
494 self.see(startup_select[0], 0)
495 elif startup_select[-1] in ("cols", "columns"):
496 self.MT.create_selection_box(
497 0,
498 startup_select[0],
499 len(self.MT.row_positions) - 1,
500 startup_select[1],
501 "columns",
502 )
503 self.see(0, startup_select[0])
504 except Exception:
505 pass
506 self.refresh()
507 if startup_focus:
508 self.MT.focus_set()
509 self.after_idle(self.startup_complete)
510
511 def startup_complete(self, _mod: bool = True) -> bool:
512 self._startup_complete = _mod
513 return self._startup_complete
514
515 # Sheet Colors
516
517 def change_theme(self, theme: str = "light blue", redraw: bool = True) -> Sheet:
518 if theme.lower() in ("light blue", "light_blue"):
519 self.set_options(**theme_light_blue, redraw=False)
520 self.config(bg=theme_light_blue["table_bg"])
521 elif theme.lower() == "dark":
522 self.set_options(**theme_dark, redraw=False)
523 self.config(bg=theme_dark["table_bg"])
524 elif theme.lower() in ("light green", "light_green"):
525 self.set_options(**theme_light_green, redraw=False)
526 self.config(bg=theme_light_green["table_bg"])
527 elif theme.lower() in ("dark blue", "dark_blue"):
528 self.set_options(**theme_dark_blue, redraw=False)
529 self.config(bg=theme_dark_blue["table_bg"])
530 elif theme.lower() in ("dark green", "dark_green"):
531 self.set_options(**theme_dark_green, redraw=False)
532 self.config(bg=theme_dark_green["table_bg"])
533 elif theme.lower() == "black":
534 self.set_options(**theme_black, redraw=False)
535 self.config(bg=theme_black["table_bg"])
536 self.MT.recreate_all_selection_boxes()
537 self.set_refresh_timer(redraw)
538 self.TL.redraw()
539 return self
540
541 # Header and Index
542
543 def set_header_data(
544 self,
545 value: Any,
546 c: int | None | Iterator[int] = None,
547 redraw: bool = True,
548 ) -> Sheet:
549 if c is None:
550 if not isinstance(value, int) and not is_iterable(value):
551 raise ValueError(f"Argument 'value' must be non-string iterable or int, not {type(value)} type.")
552 if not isinstance(value, list) and not isinstance(value, int):
553 value = list(value)
554 self.MT._headers = value
555 elif isinstance(c, int):
556 self.CH.set_cell_data(c, value)
557 elif is_iterable(value) and is_iterable(c):
558 for c_, v in zip(c, value):
559 self.CH.set_cell_data(c_, v)
560 return self.set_refresh_timer(redraw)
561
562 def headers(
563 self,
564 newheaders: Any = None,
565 index: None | int = None,
566 reset_col_positions: bool = False,
567 show_headers_if_not_sheet: bool = True,
568 redraw: bool = True,
569 ) -> Any:
570 self.set_refresh_timer(redraw)
571 return self.MT.headers(
572 newheaders,
573 index,
574 reset_col_positions=reset_col_positions,
575 show_headers_if_not_sheet=show_headers_if_not_sheet,
576 redraw=False,
577 )
578
579 def set_index_data(
580 self,
581 value: Any,
582 r: int | None | Iterator[int] = None,
583 redraw: bool = True,
584 ) -> Sheet:
585 if r is None:
586 if not isinstance(value, int) and not is_iterable(value):
587 raise ValueError(f"Argument 'value' must be non-string iterable or int, not {type(value)} type.")
588 if not isinstance(value, list) and not isinstance(value, int):
589 value = list(value)
590 self.MT._row_index = value
591 elif isinstance(r, int):
592 self.RI.set_cell_data(r, value)
593 elif is_iterable(value) and is_iterable(r):
594 for r_, v in zip(r, value):
595 self.RI.set_cell_data(r_, v)
596 return self.set_refresh_timer(redraw)
597
598 def row_index(
599 self,
600 newindex: Any = None,
601 index: None | int = None,
602 reset_row_positions: bool = False,
603 show_index_if_not_sheet: bool = True,
604 redraw: bool = True,
605 ) -> Any:
606 self.set_refresh_timer(redraw)
607 return self.MT.row_index(
608 newindex,
609 index,
610 reset_row_positions=reset_row_positions,
611 show_index_if_not_sheet=show_index_if_not_sheet,
612 redraw=False,
613 )
614
615 # Bindings and Functionality
616
617 def enable_bindings(self, *bindings: Binding) -> Sheet:
618 self.MT.enable_bindings(bindings)
619 return self
620
621 def disable_bindings(self, *bindings: Binding) -> Sheet:
622 self.MT.disable_bindings(bindings)
623 return self
624
625 def extra_bindings(
626 self,
627 bindings: ExtraBinding | Sequence[ExtraBinding] | None = None,
628 func: Callable | None = None,
629 ) -> Sheet:
630 # bindings is None, unbind all
631 if bindings is None:
632 bindings = "all"
633 # bindings is str, func arg is None or Callable
634 if isinstance(bindings, str):
635 iterable = ((bindings, func),)
636 # bindings is list or tuple of strings, func arg is None or Callable
637 elif is_iterable(bindings) and isinstance(bindings[0], str):
638 iterable = ((b, func) for b in bindings)
639 # bindings is a list or tuple of two tuples or lists
640 # in this case the func arg is ignored
641 # e.g. [(binding, function), (binding, function), ...]
642 elif is_iterable(bindings):
643 iterable = bindings
644
645 for b, f in iterable:
646 b = b.lower()
647 if f is not None and b in emitted_events:
648 self.bind(b, f)
649 # Handle group bindings
650 if b in ("all", "bind_all", "unbind_all"):
651 for component, attr in ALL_BINDINGS:
652 setattr(getattr(self, component), attr, f)
653 elif b in ("all_select_events", "select", "selectevents", "select_events"):
654 for component, attr in SELECT_BINDINGS:
655 setattr(getattr(self, component), attr, f)
656 elif b in ("all_modified_events", "sheetmodified", "sheet_modified", "modified_events", "modified"):
657 for component, attr in MODIFIED_BINDINGS:
658 setattr(getattr(self, component), attr, f)
659 # Handle individual bindings
660 elif b in BINDING_TO_ATTR:
661 component, attr = BINDING_TO_ATTR[b]
662 setattr(getattr(self, component), attr, f)
663 return self
664
665 def bind(
666 self,
667 binding: str,
668 func: Callable,
669 add: str | None = None,
670 ) -> Sheet:
671 """
672 In addition to normal use, the following special tksheet bindings can be used:
673 - "<<SheetModified>>"
674 - "<<SheetRedrawn>>"
675 - "<<SheetSelect>>"
676 - "<<Copy>>"
677 - "<<Cut>>"
678 - "<<Paste>>"
679 - "<<Delete>>"
680 - "<<Undo>>"
681 - "<<Redo>>"
682 - "<<SelectAll>>"
683
684 Use `add` parameter to bind to multiple functions
685 """
686 if binding == "<ButtonPress-1>":
687 self.MT.extra_b1_press_func = func
688 self.CH.extra_b1_press_func = func
689 self.RI.extra_b1_press_func = func
690 self.TL.extra_b1_press_func = func
691 elif binding == "<ButtonMotion-1>":
692 self.MT.extra_b1_motion_func = func
693 self.CH.extra_b1_motion_func = func
694 self.RI.extra_b1_motion_func = func
695 self.TL.extra_b1_motion_func = func
696 elif binding == "<ButtonRelease-1>":
697 self.MT.extra_b1_release_func = func
698 self.CH.extra_b1_release_func = func
699 self.RI.extra_b1_release_func = func
700 self.TL.extra_b1_release_func = func
701 elif binding == "<Double-Button-1>":
702 self.MT.extra_double_b1_func = func
703 self.CH.extra_double_b1_func = func
704 self.RI.extra_double_b1_func = func
705 self.TL.extra_double_b1_func = func
706 elif binding == "<Motion>":
707 self.MT.extra_motion_func = func
708 self.CH.extra_motion_func = func
709 self.RI.extra_motion_func = func
710 self.TL.extra_motion_func = func
711 elif binding == rc_binding:
712 self.MT.extra_rc_func = func
713 self.CH.extra_rc_func = func
714 self.RI.extra_rc_func = func
715 self.TL.extra_rc_func = func
716 elif binding in emitted_events:
717 if add:
718 self.bound_events[binding].append(func)
719 else:
720 self.bound_events[binding] = [func]
721 else:
722 self.MT.bind(binding, func, add=add)
723 self.CH.bind(binding, func, add=add)
724 self.RI.bind(binding, func, add=add)
725 self.TL.bind(binding, func, add=add)
726 return self
727
728 def unbind(self, binding: str) -> Sheet:
729 if binding in emitted_events:
730 self.bound_events[binding] = []
731 elif binding == "<ButtonPress-1>":
732 self.MT.extra_b1_press_func = None
733 self.CH.extra_b1_press_func = None
734 self.RI.extra_b1_press_func = None
735 self.TL.extra_b1_press_func = None
736 elif binding == "<ButtonMotion-1>":
737 self.MT.extra_b1_motion_func = None
738 self.CH.extra_b1_motion_func = None
739 self.RI.extra_b1_motion_func = None
740 self.TL.extra_b1_motion_func = None
741 elif binding == "<ButtonRelease-1>":
742 self.MT.extra_b1_release_func = None
743 self.CH.extra_b1_release_func = None
744 self.RI.extra_b1_release_func = None
745 self.TL.extra_b1_release_func = None
746 elif binding == "<Double-Button-1>":
747 self.MT.extra_double_b1_func = None
748 self.CH.extra_double_b1_func = None
749 self.RI.extra_double_b1_func = None
750 self.TL.extra_double_b1_func = None
751 elif binding == "<Motion>":
752 self.MT.extra_motion_func = None
753 self.CH.extra_motion_func = None
754 self.RI.extra_motion_func = None
755 self.TL.extra_motion_func = None
756 elif binding == rc_binding:
757 self.MT.extra_rc_func = None
758 self.CH.extra_rc_func = None
759 self.RI.extra_rc_func = None
760 self.TL.extra_rc_func = None
761 else:
762 self.MT.unbind(binding)
763 self.CH.unbind(binding)
764 self.RI.unbind(binding)
765 self.TL.unbind(binding)
766 return self
767
768 def edit_validation(self, func: Callable | None = None) -> Sheet:
769 if not isinstance(func, (Callable, None)):
770 raise ValueError("Argument must be either Callable or None.")
771 self.MT.edit_validation_func = func
772 return self
773
774 def bulk_table_edit_validation(self, func: Callable | None = None) -> Sheet:
775 if not isinstance(func, (Callable, None)):
776 raise ValueError("Argument must be either Callable or None.")
777 self.MT.bulk_table_edit_validation_func = func
778 return self
779
780 def popup_menu_add_command(
781 self,
782 label: str,
783 func: Callable,
784 table_menu: bool = True,
785 index_menu: bool = True,
786 header_menu: bool = True,
787 empty_space_menu: bool = True,
788 ) -> Sheet:
789 if label not in self.MT.extra_table_rc_menu_funcs and table_menu:
790 self.MT.extra_table_rc_menu_funcs[label] = func
791 if label not in self.MT.extra_index_rc_menu_funcs and index_menu:
792 self.MT.extra_index_rc_menu_funcs[label] = func
793 if label not in self.MT.extra_header_rc_menu_funcs and header_menu:
794 self.MT.extra_header_rc_menu_funcs[label] = func
795 if label not in self.MT.extra_empty_space_rc_menu_funcs and empty_space_menu:
796 self.MT.extra_empty_space_rc_menu_funcs[label] = func
797 self.MT.create_rc_menus()
798 return self
799
800 def popup_menu_del_command(self, label: str | None = None) -> Sheet:
801 if label is None:
802 self.MT.extra_table_rc_menu_funcs = {}
803 self.MT.extra_index_rc_menu_funcs = {}
804 self.MT.extra_header_rc_menu_funcs = {}
805 self.MT.extra_empty_space_rc_menu_funcs = {}
806 else:
807 if label in self.MT.extra_table_rc_menu_funcs:
808 del self.MT.extra_table_rc_menu_funcs[label]
809 if label in self.MT.extra_index_rc_menu_funcs:
810 del self.MT.extra_index_rc_menu_funcs[label]
811 if label in self.MT.extra_header_rc_menu_funcs:
812 del self.MT.extra_header_rc_menu_funcs[label]
813 if label in self.MT.extra_empty_space_rc_menu_funcs:
814 del self.MT.extra_empty_space_rc_menu_funcs[label]
815 self.MT.create_rc_menus()
816 return self
817
818 def basic_bindings(self, enable: bool = False) -> Sheet:
819 for canvas in (self.MT, self.CH, self.RI, self.TL):
820 canvas.basic_bindings(enable)
821 return self
822
823 def cut(self, event: Any = None, validation: bool = True) -> None | EventDataDict:
824 return self.MT.ctrl_x(event, validation)
825
826 def copy(self, event: Any = None) -> None | EventDataDict:
827 return self.MT.ctrl_c(event)
828
829 def paste(self, event: Any = None, validation: bool = True) -> None | EventDataDict:
830 return self.MT.ctrl_v(event, validation)
831
832 def delete(self, event: Any = None, validation: bool = True) -> None | EventDataDict:
833 return self.MT.delete_key(event, validation)
834
835 def undo(self, event: Any = None) -> None | EventDataDict:
836 return self.MT.undo(event)
837
838 def redo(self, event: Any = None) -> None | EventDataDict:
839 return self.MT.redo(event)
840
841 def has_focus(self) -> bool:
842 """
843 Check if any Sheet widgets have focus
844 Includes child widgets such as scroll bars
845 Returns bool
846 """
847 try:
848 widget = self.focus_get()
849 return widget == self or any(widget == c for c in self.children.values())
850 except Exception:
851 return False
852
853 def focus_set(
854 self,
855 canvas: Literal[
856 "table",
857 "header",
858 "row_index",
859 "index",
860 "topleft",
861 "top_left",
862 ] = "table",
863 ) -> Sheet:
864 if canvas == "table":
865 self.MT.focus_set()
866 elif canvas == "header":
867 self.CH.focus_set()
868 elif canvas in ("row_index", "index"):
869 self.RI.focus_set()
870 elif canvas in ("topleft", "top_left"):
871 self.TL.focus_set()
872 return self
873
874 def zoom_in(self) -> Sheet:
875 self.MT.zoom_in()
876 return self
877
878 def zoom_out(self) -> Sheet:
879 self.MT.zoom_out()
880 return self
881
882 @property
883 def event(self) -> EventDataDict:
884 return self.last_event_data
885
886 # Span objects
887
888 def span(
889 self,
890 *key: CreateSpanTypes,
891 type_: str = "",
892 name: str = "",
893 table: bool = True,
894 index: bool = False,
895 header: bool = False,
896 tdisp: bool = False,
897 idisp: bool = True,
898 hdisp: bool = True,
899 transposed: bool = False,
900 ndim: int = 0,
901 convert: Any = None,
902 undo: bool = True,
903 emit_event: bool = False,
904 widget: Any = None,
905 expand: None | str = None,
906 formatter_options: dict | None = None,
907 **kwargs,
908 ) -> Span:
909 """
910 Create a span / get an existing span by name
911 Returns the created span
912 """
913 if name and name in self.MT.named_spans:
914 return self.MT.named_spans[name]
915 elif not name:
916 name = num2alpha(self.named_span_id)
917 self.named_span_id += 1
918 while name in self.MT.named_spans:
919 name = num2alpha(self.named_span_id)
920 self.named_span_id += 1
921 span = self.span_from_key(*key)
922 span.name = name
923 if expand is not None:
924 span.expand(expand)
925 if isinstance(formatter_options, dict):
926 span.type_ = "format"
927 span.kwargs = {"formatter": None, **formatter_options}
928 else:
929 span.type_ = type_.lower()
930 span.kwargs = kwargs
931 span.table = table
932 span.header = header
933 span.index = index
934 span.tdisp = tdisp
935 span.idisp = idisp
936 span.hdisp = hdisp
937 span.transposed = transposed
938 span.ndim = ndim
939 span.convert = convert
940 span.undo = undo
941 span.emit_event = emit_event
942 span.widget = self if widget is None else widget
943 return span
944
945 # Named Spans
946
947 def named_span(self, span: Span) -> Span:
948 if span.name in self.MT.named_spans:
949 raise ValueError(f"Span '{span.name}' already exists.")
950 if not span.name:
951 raise ValueError("Span must have a name.")
952 if span.type_ not in named_span_types:
953 raise ValueError(f"Span 'type_' must be one of the following: {', '.join(named_span_types)}.")
954 self.MT.named_spans[span.name] = span
955 self.create_options_from_span(span)
956 return span
957
958 def create_options_from_span(self, span: Span) -> Sheet:
959 getattr(self, span.type_)(span, **span.kwargs)
960 return self
961
962 def del_named_span(self, name: str) -> Sheet:
963 if name not in self.MT.named_spans:
964 raise ValueError(f"Span '{name}' does not exist.")
965 span = self.MT.named_spans[name]
966 type_ = span.type_
967 from_r, from_c, upto_r, upto_c = self.MT.named_span_coords(name)
968 totalrows = self.MT.get_max_row_idx() + 1
969 totalcols = self.MT.get_max_column_idx() + 1
970 rng_from_r = 0 if from_r is None else from_r
971 rng_from_c = 0 if from_c is None else from_c
972 rng_upto_r = totalrows if upto_r is None else upto_r
973 rng_upto_c = totalcols if upto_c is None else upto_c
974 if span["header"]:
975 del_named_span_options(
976 self.CH.cell_options,
977 range(rng_from_c, rng_upto_c),
978 type_,
979 )
980 if span["index"]:
981 del_named_span_options(
982 self.RI.cell_options,
983 range(rng_from_r, rng_upto_r),
984 type_,
985 )
986 # col options
987 if from_r is None:
988 del_named_span_options(
989 self.MT.col_options,
990 range(rng_from_c, rng_upto_c),
991 type_,
992 )
993 # row options
994 elif from_c is None:
995 del_named_span_options(
996 self.MT.row_options,
997 range(rng_from_r, rng_upto_r),
998 type_,
999 )
1000 # cell options
1001 elif isinstance(from_r, int) and isinstance(from_c, int):
1002 del_named_span_options_nested(
1003 self.MT.cell_options,
1004 range(rng_from_r, rng_upto_r),
1005 range(rng_from_c, rng_upto_c),
1006 type_,
1007 )
1008 del self.MT.named_spans[name]
1009 return self
1010
1011 def set_named_spans(self, named_spans: None | dict[str, Span] = None) -> Sheet:
1012 if named_spans is None:
1013 for name in self.MT.named_spans:
1014 self.del_named_span(name)
1015 named_spans = {}
1016 self.MT.named_spans = named_spans
1017 return self
1018
1019 def get_named_span(self, name: str) -> dict[str, Span]:
1020 return self.MT.named_spans[name]
1021
1022 def get_named_spans(self) -> dict[str, Span]:
1023 return self.MT.named_spans
1024
1025 # Getting Sheet Data
1026
1027 def __getitem__(
1028 self,
1029 *key: CreateSpanTypes,
1030 ) -> Span:
1031 return self.span_from_key(*key)
1032
1033 def span_from_key(self, *key: CreateSpanTypes) -> None | Span:
1034 if not key:
1035 key = (None, None, None, None)
1036 span = key_to_span(key if len(key) != 1 else key[0], self.MT.named_spans, self)
1037 if isinstance(span, str):
1038 raise ValueError(span)
1039 return span
1040
1041 def ranges_from_span(self, span: Span) -> tuple[Generator, Generator]:
1042 return span_ranges(
1043 span,
1044 totalrows=self.MT.total_data_rows,
1045 totalcols=self.MT.total_data_cols,
1046 )
1047
1048 def get_data(self, *key: CreateSpanTypes) -> Any:
1049 """
1050 e.g. retrieves entire table as pandas dataframe
1051 sheet["A1"].expand().options(convert=pandas.DataFrame).data
1052
1053 must deal with
1054 - format
1055 - transpose
1056 - ndim
1057 - index
1058 - header
1059 - tdisp
1060 - idisp
1061 - hdisp
1062 - convert
1063
1064 format
1065 - if span.type_ == "format" and span.kwargs
1066 - does not format the sheets internal data, only data being returned
1067 - formats the data before retrieval with specified formatter function e.g.
1068 - format=int_formatter() -> returns kwargs, span["kwargs"] now has formatter kwargs
1069 - uses format_data(value=cell, **span["kwargs"]) on every table cell returned
1070
1071 tranpose
1072 - make sublists become columns rather than rows
1073 - no effect on single cell
1074
1075 ndim
1076 - defaults to None
1077 - when None it will follow rules:
1078 - if single cell in a list of lists return single cell
1079 - if single sublist in a list of lists then return single list
1080 - when ndim == 1 force single list
1081 - when ndim == 2 force list of lists
1082
1083 table
1084 - gets table data, if false table data will not be included
1085
1086 index
1087 - gets index data, is at the beginning of each row normally
1088 becomes its own column if transposed
1089
1090 header
1091 - get header data, is its own row normally
1092 goes at the top of each column if transposed
1093
1094 tdisp
1095 - if True gets displayed sheet values instead of actual data
1096
1097 idisp
1098 - if True gets displayed index values instead of actual data
1099
1100 hdisp
1101 - if True gets displayed header values instead of actual data
1102
1103 convert
1104 - instead of returning data normally it returns
1105 convert(data) - sends the data to an optional convert function
1106
1107 """
1108 span = self.span_from_key(*key)
1109 rows, cols = self.ranges_from_span(span)
1110 table, index, header = span.table, span.index, span.header
1111 fmt_kw = span.kwargs if span.type_ == "format" and span.kwargs else None
1112 t_data = partial(self.MT.get_cell_data, get_displayed=True) if span.tdisp else self.MT.get_cell_data
1113 i_data = self.RI.cell_str if span.idisp else self.RI.get_cell_data
1114 h_data = self.CH.cell_str if span.hdisp else self.CH.get_cell_data
1115 res = []
1116 if span.transposed:
1117 # Index row (first row when transposed)
1118 if index:
1119 index_row = [""] if header and table else []
1120 index_row.extend(i_data(r) for r in rows)
1121 res.append(index_row)
1122 # Header and/or table data as columns
1123 if header:
1124 for c in cols:
1125 col = [h_data(c)]
1126 if table:
1127 col.extend(t_data(r, c, fmt_kw=fmt_kw) for r in rows)
1128 res.append(col)
1129 elif table:
1130 res.extend([t_data(r, c, fmt_kw=fmt_kw) for r in rows] for c in cols)
1131 else:
1132 # Header row
1133 if header:
1134 header_row = [""] if index and table else []
1135 header_row.extend(h_data(c) for c in cols)
1136 res.append(header_row)
1137 # Index and/or table data as rows
1138 if index:
1139 for r in rows:
1140 row = [i_data(r)]
1141 if table:
1142 row.extend(t_data(r, c, fmt_kw=fmt_kw) for c in cols)
1143 res.append(row)
1144 elif table:
1145 res.extend([t_data(r, c, fmt_kw=fmt_kw) for c in cols] for r in rows)
1146
1147 if not span.ndim:
1148 # it's a cell
1149 if len(res) == 1 and len(res[0]) == 1:
1150 res = res[0][0]
1151 # it's a single sublist
1152 elif len(res) == 1:
1153 res = res[0]
1154 # retrieving a list of index cells or
1155 elif (index and not span.transposed and not table and not header) or (
1156 # it's a column that's spread across sublists
1157 table and res and not span.transposed and len(res[0]) == 1 and len(res[-1]) == 1
1158 ):
1159 res = list(chain.from_iterable(res))
1160 elif span.ndim == 1:
1161 # flatten sublists
1162 res = res[0] if len(res) == 1 and len(res[0]) == 1 else list(chain.from_iterable(res))
1163 # if span.ndim == 2 res keeps its current dimensions as a list of lists
1164
1165 if span.convert is None:
1166 return res
1167 else:
1168 return span.convert(res)
1169
1170 def get_total_rows(self, include_index: bool = False) -> int:
1171 return self.MT.total_data_rows(include_index=include_index)
1172
1173 def get_total_columns(self, include_header: bool = False) -> int:
1174 return self.MT.total_data_cols(include_header=include_header)
1175
1176 def get_value_for_empty_cell(
1177 self,
1178 r: int,
1179 c: int,
1180 r_ops: bool = True,
1181 c_ops: bool = True,
1182 ) -> Any:
1183 return self.MT.get_value_for_empty_cell(r, c, r_ops, c_ops)
1184
1185 @property
1186 def data(self) -> Sequence[Sequence[Any]]:
1187 return self.MT.data
1188
1189 def __iter__(self) -> Iterator[list[Any] | tuple[Any]]:
1190 return self.MT.data.__iter__()
1191
1192 def __reversed__(self) -> Iterator[list[Any] | tuple[Any]]:
1193 return reversed(self.MT.data)
1194
1195 def __contains__(self, key: Any) -> bool:
1196 if isinstance(key, (list, tuple)):
1197 return key in self.MT.data
1198 return any(key in row for row in self.MT.data)
1199
1200 # Setting Sheet Data
1201
1202 def reset(
1203 self,
1204 table: bool = True,
1205 header: bool = True,
1206 index: bool = True,
1207 row_heights: bool = True,
1208 column_widths: bool = True,
1209 cell_options: bool = True,
1210 tags: bool = True,
1211 undo_stack: bool = True,
1212 selections: bool = True,
1213 sheet_options: bool = False,
1214 displayed_rows: bool = True,
1215 displayed_columns: bool = True,
1216 tree: bool = True,
1217 redraw: bool = True,
1218 ) -> Sheet:
1219 if table:
1220 self.MT.hide_text_editor_and_dropdown(redraw=False)
1221 self.MT.data = []
1222 if header:
1223 self.CH.hide_text_editor_and_dropdown(redraw=False)
1224 self.MT._headers = []
1225 if index:
1226 self.RI.hide_text_editor_and_dropdown(redraw=False)
1227 self.MT._row_index = []
1228 if displayed_columns:
1229 self.MT.displayed_columns = []
1230 self.MT.all_columns_displayed = True
1231 if displayed_rows:
1232 self.MT.displayed_rows = []
1233 self.MT.all_rows_displayed = True
1234 if selections:
1235 self.MT.deselect(redraw=False)
1236 if row_heights:
1237 self.MT.saved_row_heights = {}
1238 self.MT.set_row_positions([])
1239 if column_widths:
1240 self.MT.saved_column_widths = {}
1241 self.MT.set_col_positions([])
1242 if cell_options:
1243 self.reset_all_options()
1244 if tags:
1245 self.MT.reset_tags()
1246 if undo_stack:
1247 self.reset_undos()
1248 if sheet_options:
1249 self.ops = new_sheet_options()
1250 self.change_theme(redraw=False)
1251 if tree:
1252 self.RI.tree_reset()
1253 if tree or row_heights or column_widths:
1254 self.MT.hide_dropdown_editor_all_canvases()
1255 return self.set_refresh_timer(redraw)
1256
1257 def set_sheet_data(
1258 self,
1259 data: list | tuple | None = None,
1260 reset_col_positions: bool = True,
1261 reset_row_positions: bool = True,
1262 redraw: bool = True,
1263 verify: bool = False,
1264 reset_highlights: bool = False,
1265 keep_formatting: bool = True,
1266 delete_options: bool = False,
1267 ) -> Any:
1268 if data is None:
1269 data = []
1270 if verify and (not isinstance(data, list) or not all(isinstance(row, list) for row in data)):
1271 raise ValueError("Data argument must be a list of lists, sublists being rows")
1272 if delete_options:
1273 self.reset_all_options()
1274 elif reset_highlights:
1275 self.dehighlight_all()
1276 return self.MT.data_reference(
1277 data,
1278 reset_col_positions,
1279 reset_row_positions,
1280 redraw,
1281 return_id=False,
1282 keep_formatting=keep_formatting,
1283 )
1284
1285 @data.setter
1286 def data(self, value: list[list[Any]]) -> None:
1287 self.data_reference(value)
1288
1289 def new_tksheet_event(self) -> EventDataDict:
1290 return event_dict(
1291 name="",
1292 sheet=self.name,
1293 widget=self,
1294 selected=self.MT.selected,
1295 )
1296
1297 def set_data(
1298 self,
1299 *key: CreateSpanTypes,
1300 data: Any = None,
1301 undo: bool | None = None,
1302 emit_event: bool | None = None,
1303 redraw: bool = True,
1304 event_data: EventDataDict | None = None,
1305 ) -> EventDataDict:
1306 """
1307 e.g.
1308 df = pandas.DataFrame([[1, 2, 3], [4, 5, 6]])
1309 sheet["A1"] = df.values.tolist()
1310
1311 just uses the spans from_r, from_c values
1312
1313 'data' parameter could be:
1314 - list of lists
1315 - list of values
1316 - not a list or tuple
1317 - can have all three of the below set at the same time
1318 or just one or two:
1319 - if span.table then sets table cell
1320 - if span.index then sets index cell
1321 - if span.header than sets header cell
1322
1323 expands sheet if required but can only undo any added
1324 displayed row/column positions, not expanded MT.data list
1325
1326 format
1327 - if span.type_ == "format" and span.kwargs
1328 - formats the data before setting with specified formatter function e.g.
1329 - format=int_formatter() -> returns kwargs, span["kwargs"] now has formatter kwargs
1330 - uses format_data(value=cell, **span["kwargs"]) on every set cell
1331
1332 transposed
1333 - switches range orientation
1334 - a single list will go to row without transposed
1335 - multi lists will go to rows without transposed
1336 - with transposed a single list will go to column
1337 - with transposed multi lists will go to columns
1338
1339 header
1340 - assumes there's a header, sets header cell data as well
1341
1342 index
1343 - assumes there's an index, sets index cell data as well
1344
1345 undo
1346 - if True adds to undo stack and if undo is enabled
1347 for end user they can undo/redo the change
1348
1349 in the table comments below -
1350 - t stands for table
1351 - i stands for index
1352 - h stands for header
1353
1354 """
1355 span = self.span_from_key(*key)
1356 startr, startc = span_froms(span)
1357 table, index, header = span.table, span.index, span.header
1358 fmt_kw = span.kwargs if span.type_ == "format" and span.kwargs else None
1359 transposed = span.transposed
1360 maxr, maxc = startr, startc
1361 if event_data is None:
1362 event_data = event_dict(
1363 name="edit_table",
1364 sheet=self.name,
1365 widget=self,
1366 selected=self.MT.selected,
1367 )
1368 set_t = self.event_data_set_table_cell
1369 set_i, set_h = self.event_data_set_index_cell, self.event_data_set_header_cell
1370 istart = 1 if index else 0
1371 hstart = 1 if header else 0
1372 # data is list
1373 if isinstance(data, (list, tuple)):
1374 if not data:
1375 return
1376 # data is a list of lists
1377 if isinstance(data[0], (list, tuple)):
1378 if transposed:
1379 if table:
1380 """
1381 - sublists are columns
1382 1 2 3
1383 A [[-, i, i],
1384 B [h, t, t],
1385 C [h, t, t],]
1386 """
1387 if index:
1388 for r, v in enumerate(islice(data[0], hstart, None)):
1389 maxr = r
1390 event_data = set_i(r, v, event_data)
1391 if header:
1392 for c, sl in enumerate(islice(data, istart, None), start=startc):
1393 maxc = c
1394 for v in islice(sl, 0, 1):
1395 event_data = set_h(c, v, event_data)
1396 for c, sl in enumerate(islice(data, istart, None), start=startc):
1397 maxc = c
1398 for r, v in enumerate(islice(sl, hstart, None), start=startr):
1399 event_data = set_t(r, c, v, event_data, fmt_kw)
1400 maxr = r
1401 elif not table:
1402 if index and header:
1403 """
1404 - first sublist is index, rest are headers
1405 [['1', '2', '3'], ['A'], ['B'], ['C']]
1406 """
1407 for r, v in enumerate(data[0], start=startr):
1408 maxr = r
1409 event_data = set_i(r, v, event_data)
1410 for c, sl in enumerate(islice(data, 1, None), start=startc):
1411 maxc = c
1412 if sl:
1413 event_data = set_h(c, sl[0], event_data)
1414 elif index:
1415 """
1416 ['1', '2', '3']
1417 """
1418 for r, v in enumerate(data, start=startr):
1419 maxr = r
1420 event_data = set_i(r, v, event_data)
1421 elif header:
1422 """
1423 [['A'], ['B'], ['C']]
1424 """
1425 for c, sl in enumerate(data, start=startc):
1426 maxc = c
1427 if sl:
1428 event_data = set_h(c, sl[0], event_data)
1429 elif not transposed:
1430 if table:
1431 """
1432 - sublists are rows
1433 A B C
1434 1 [[-, h, h],
1435 2 [i, t, t],
1436 3 [i, t, t],]
1437 """
1438 if index:
1439 for r, sl in enumerate(islice(data, hstart, None), start=startr):
1440 maxr = r
1441 for v in islice(sl, 0, 1):
1442 event_data = set_i(r, v, event_data)
1443 if header:
1444 for c, v in enumerate(islice(data[0], istart, None)):
1445 maxc = c
1446 event_data = set_h(c, v, event_data)
1447 for r, sl in enumerate(islice(data, hstart, None), start=startr):
1448 maxr = r
1449 for c, v in enumerate(islice(sl, istart, None), start=startc):
1450 maxc = c
1451 event_data = set_t(r, c, v, event_data, fmt_kw)
1452 elif not table:
1453 if index and header:
1454 """
1455 - first sublist is headers, rest are index values
1456 [['A', 'B', 'C'], ['1'], ['2'], ['3']]
1457 """
1458 for c, v in enumerate(data[0], start=startc):
1459 maxc = c
1460 event_data = set_h(c, v, event_data)
1461 for r, sl in enumerate(islice(data, 1, None), start=startr):
1462 maxr = r
1463 if sl:
1464 event_data = set_i(r, sl[0], event_data)
1465 elif index:
1466 """
1467 [['1'], ['2'], ['3']]
1468 """
1469 for r, sl in enumerate(data, start=startr):
1470 maxr = r
1471 if sl:
1472 event_data = set_i(r, sl[0], event_data)
1473 elif header:
1474 """
1475 ['A', 'B', 'C']
1476 """
1477 for c, v in enumerate(data, start=startc):
1478 maxc = c
1479 event_data = set_h(c, v, event_data)
1480 # data is list of values
1481 else:
1482 # setting a list of index values, ignore transposed
1483 if index and not table:
1484 """
1485 1 2 3
1486 [i, i, i]
1487 """
1488 for r, v in enumerate(data, start=startr):
1489 maxr = r
1490 event_data = set_i(r, v, event_data)
1491 # setting a list of header values, ignore transposed
1492 elif header and not table:
1493 """
1494 A B C
1495 [h, h, h]
1496 """
1497 for c, v in enumerate(data, start=startc):
1498 maxc = c
1499 event_data = set_h(c, v, event_data)
1500 # includes table values, transposed taken into account
1501 elif table:
1502 if transposed:
1503 """
1504 - single list is column, span.index ignored
1505 1 2 3
1506 A [h, t, t]
1507 """
1508 if header:
1509 event_data = set_h(startc, data[0], event_data)
1510 for r, v in enumerate(islice(data, hstart, None), start=startr):
1511 maxr = r
1512 event_data = set_t(r, startc, v, event_data, fmt_kw)
1513 elif not transposed:
1514 """
1515 - single list is row, span.header ignored
1516 A B C
1517 1 [i, t, t]
1518 """
1519 if index:
1520 event_data = set_i(startr, data[0], event_data)
1521 for c, v in enumerate(islice(data, istart, None), start=startc):
1522 maxc = c
1523 event_data = set_t(startr, c, v, event_data, fmt_kw)
1524 # data is a value
1525 else:
1526 """
1527 A
1528 1 t/i/h
1529 """
1530 if table:
1531 event_data = set_t(startr, startc, data, event_data, fmt_kw)
1532 if index:
1533 event_data = set_i(startr, data, event_data)
1534 if header:
1535 event_data = set_h(startc, data, event_data)
1536 # add row/column lines (positions) if required
1537 if self.MT.all_columns_displayed and maxc >= (ncols := len(self.MT.col_positions) - 1):
1538 _, _, widths = self.MT.get_args_for_add_columns(
1539 data_ins_col=len(self.MT.col_positions) - 1,
1540 displayed_ins_col=len(self.MT.col_positions) - 1,
1541 columns=maxc + 1 - ncols,
1542 widths=None,
1543 headers=False,
1544 )
1545 event_data = self.MT.add_columns(
1546 columns={},
1547 header={},
1548 column_widths=widths,
1549 event_data=event_data,
1550 create_selections=False,
1551 )
1552 if self.MT.all_rows_displayed and maxr >= (nrows := len(self.MT.row_positions) - 1):
1553 _, _, heights = self.MT.get_args_for_add_rows(
1554 data_ins_row=len(self.MT.row_positions) - 1,
1555 displayed_ins_row=len(self.MT.row_positions) - 1,
1556 rows=maxr + 1 - nrows,
1557 heights=None,
1558 row_index=False,
1559 )
1560 event_data = self.MT.add_rows(
1561 rows={},
1562 index={},
1563 row_heights=heights,
1564 event_data=event_data,
1565 create_selections=False,
1566 )
1567 if (
1568 event_data["cells"]["table"]
1569 or event_data["cells"]["index"]
1570 or event_data["cells"]["header"]
1571 or event_data["added"]["columns"]
1572 or event_data["added"]["rows"]
1573 ):
1574 if undo is True or (undo is None and span.undo):
1575 self.MT.undo_stack.append(stored_event_dict(event_data))
1576 if emit_event is True or (emit_event is None and span.emit_event):
1577 self.emit_event("<<SheetModified>>", event_data)
1578 self.set_refresh_timer(redraw)
1579 return event_data
1580
1581 def clear(
1582 self,
1583 *key: CreateSpanTypes,
1584 undo: bool | None = None,
1585 emit_event: bool | None = None,
1586 redraw: bool = True,
1587 ) -> EventDataDict:
1588 span = self.span_from_key(*key)
1589 rows, cols = self.ranges_from_span(span)
1590 clear_t = self.event_data_set_table_cell
1591 clear_i = self.event_data_set_index_cell
1592 clear_h = self.event_data_set_header_cell
1593 quick_tval = self.MT.get_value_for_empty_cell
1594 quick_ival = self.RI.get_value_for_empty_cell
1595 quick_hval = self.CH.get_value_for_empty_cell
1596 table, index, header = span.table, span.index, span.header
1597 event_data = event_dict(
1598 name="edit_table",
1599 sheet=self.name,
1600 widget=self,
1601 selected=self.MT.selected,
1602 )
1603 if index:
1604 for r in rows:
1605 event_data = clear_i(r, quick_ival(r), event_data)
1606 if header:
1607 for c in cols:
1608 event_data = clear_h(c, quick_hval(c), event_data)
1609 if table:
1610 for r in rows:
1611 for c in cols:
1612 event_data = clear_t(r, c, quick_tval(r, c), event_data)
1613 if event_data["cells"]["table"] or event_data["cells"]["header"] or event_data["cells"]["index"]:
1614 if undo is True or (undo is None and span.undo):
1615 self.MT.undo_stack.append(stored_event_dict(event_data))
1616 if emit_event is True or (emit_event is None and span.emit_event):
1617 self.emit_event("<<SheetModified>>", event_data)
1618 self.set_refresh_timer(redraw)
1619 return event_data
1620
1621 def event_data_set_table_cell(
1622 self,
1623 datarn: int,
1624 datacn: int,
1625 value: Any,
1626 event_data: EventDataDict,
1627 fmt_kw: dict | None = None,
1628 check_readonly: bool = False,
1629 ) -> EventDataDict:
1630 if fmt_kw is not None or self.MT.input_valid_for_cell(datarn, datacn, value, check_readonly=check_readonly):
1631 event_data["cells"]["table"][(datarn, datacn)] = self.MT.get_cell_data(datarn, datacn)
1632 self.MT.set_cell_data(datarn, datacn, value, kwargs=fmt_kw)
1633 return event_data
1634
1635 def event_data_set_index_cell(
1636 self,
1637 datarn: int,
1638 value: Any,
1639 event_data: EventDataDict,
1640 check_readonly: bool = False,
1641 ) -> EventDataDict:
1642 if self.RI.input_valid_for_cell(datarn, value, check_readonly=check_readonly):
1643 event_data["cells"]["index"][datarn] = self.RI.get_cell_data(datarn)
1644 self.RI.set_cell_data(datarn, value)
1645 return event_data
1646
1647 def event_data_set_header_cell(
1648 self,
1649 datacn: int,
1650 value: Any,
1651 event_data: EventDataDict,
1652 check_readonly: bool = False,
1653 ) -> EventDataDict:
1654 if self.CH.input_valid_for_cell(datacn, value, check_readonly=check_readonly):
1655 event_data["cells"]["header"][datacn] = self.CH.get_cell_data(datacn)
1656 self.CH.set_cell_data(datacn, value)
1657 return event_data
1658
1659 def insert_row(
1660 self,
1661 row: list[Any] | tuple[Any] | None = None,
1662 idx: str | int | None = None,
1663 height: int | None = None,
1664 row_index: bool = False,
1665 fill: bool = True,
1666 undo: bool = True,
1667 emit_event: bool = False,
1668 redraw: bool = True,
1669 ) -> EventDataDict:
1670 return self.insert_rows(
1671 rows=1 if row is None else [row] if isinstance(row, (list, tuple)) else row,
1672 idx=idx,
1673 heights=[height] if isinstance(height, int) else height,
1674 row_index=row_index,
1675 fill=fill,
1676 undo=undo,
1677 emit_event=emit_event,
1678 redraw=redraw,
1679 )
1680
1681 def insert_column(
1682 self,
1683 column: list[Any] | tuple[Any] | None = None,
1684 idx: str | int | None = None,
1685 width: int | None = None,
1686 header: bool = False,
1687 fill: bool = True,
1688 undo: bool = True,
1689 emit_event: bool = False,
1690 redraw: bool = True,
1691 ) -> EventDataDict:
1692 return self.insert_columns(
1693 columns=1 if column is None else [column] if isinstance(column, (list, tuple)) else column,
1694 idx=idx,
1695 widths=[width] if isinstance(width, int) else width,
1696 headers=header,
1697 fill=fill,
1698 undo=undo,
1699 emit_event=emit_event,
1700 redraw=redraw,
1701 )
1702
1703 def insert_rows(
1704 self,
1705 rows: Iterator[list[Any]] | int = 1,
1706 idx: str | int | None = None,
1707 heights: list[int] | tuple[int] | None = None,
1708 row_index: bool = False,
1709 fill: bool = True,
1710 undo: bool = True,
1711 emit_event: bool = False,
1712 create_selections: bool = True,
1713 add_column_widths: bool = True,
1714 push_ops: bool = True,
1715 tree: bool = True,
1716 redraw: bool = True,
1717 ) -> EventDataDict:
1718 total_cols = None
1719 if (idx := idx_param_to_int(idx)) is None:
1720 idx = len(self.MT.data)
1721 if isinstance(rows, int):
1722 if rows < 1:
1723 raise ValueError(f"rows arg must be greater than 0, not {rows}")
1724 elif fill:
1725 total_cols = self.MT.total_data_cols() if total_cols is None else total_cols
1726 len_check = (total_cols + 1) if row_index else total_cols
1727 for rn, r in enumerate(rows):
1728 if len_check > (lnr := len(r)):
1729 r.extend(
1730 self.MT.gen_empty_row_seq(
1731 rn,
1732 end=total_cols,
1733 start=(lnr - 1) if row_index else lnr,
1734 r_ops=False,
1735 c_ops=False,
1736 )
1737 )
1738 event_data = self.MT.add_rows(
1739 *self.MT.get_args_for_add_rows(
1740 data_ins_row=idx,
1741 displayed_ins_row=idx if self.MT.all_rows_displayed else bisect_left(self.MT.displayed_rows, idx),
1742 rows=rows,
1743 heights=heights,
1744 row_index=row_index,
1745 ),
1746 add_col_positions=add_column_widths,
1747 event_data=self.MT.new_event_dict("add_rows", state=True),
1748 create_selections=create_selections,
1749 push_ops=push_ops,
1750 tree=tree,
1751 )
1752 if undo:
1753 self.MT.undo_stack.append(stored_event_dict(event_data))
1754 if emit_event:
1755 self.emit_event("<<SheetModified>>", event_data)
1756 self.set_refresh_timer(redraw)
1757 return event_data
1758
1759 def insert_columns(
1760 self,
1761 columns: Iterator[list[Any]] | int = 1,
1762 idx: str | int | None = None,
1763 widths: list[int] | tuple[int] | None = None,
1764 headers: bool = False,
1765 fill: bool = True,
1766 undo: bool = True,
1767 emit_event: bool = False,
1768 create_selections: bool = True,
1769 add_row_heights: bool = True,
1770 push_ops: bool = True,
1771 redraw: bool = True,
1772 ) -> EventDataDict:
1773 old_total = self.MT.equalize_data_row_lengths()
1774 total_rows = self.MT.total_data_rows()
1775 if (idx := idx_param_to_int(idx)) is None:
1776 idx = old_total
1777 if isinstance(columns, int):
1778 if columns < 1:
1779 raise ValueError(f"columns arg must be greater than 0, not {columns}")
1780 elif fill:
1781 len_check = (total_rows + 1) if headers else total_rows
1782 for i, column in enumerate(columns):
1783 if (col_len := len(column)) < len_check:
1784 column += [
1785 self.MT.get_value_for_empty_cell(
1786 r,
1787 idx + i,
1788 r_ops=False,
1789 c_ops=False,
1790 )
1791 for r in range((col_len - 1) if headers else col_len, total_rows)
1792 ]
1793 event_data = self.MT.add_columns(
1794 *self.MT.get_args_for_add_columns(
1795 data_ins_col=idx,
1796 displayed_ins_col=idx if self.MT.all_columns_displayed else bisect_left(self.MT.displayed_columns, idx),
1797 columns=columns,
1798 widths=widths,
1799 headers=headers,
1800 ),
1801 add_row_positions=add_row_heights,
1802 event_data=self.MT.new_event_dict("add_columns", state=True),
1803 create_selections=create_selections,
1804 push_ops=push_ops,
1805 )
1806 if undo:
1807 self.MT.undo_stack.append(stored_event_dict(event_data))
1808 if emit_event:
1809 self.emit_event("<<SheetModified>>", event_data)
1810 self.set_refresh_timer(redraw)
1811 return event_data
1812
1813 def del_rows(
1814 self,
1815 rows: int | Iterator[int],
1816 data_indexes: bool = True,
1817 undo: bool = True,
1818 emit_event: bool = False,
1819 redraw: bool = True,
1820 ) -> EventDataDict:
1821 event_data = self.MT.delete_rows(
1822 rows=[rows] if isinstance(rows, int) else sorted(set(rows)),
1823 data_indexes=data_indexes,
1824 undo=undo,
1825 emit_event=emit_event,
1826 )
1827 self.set_refresh_timer(redraw)
1828 return event_data
1829
1830 del_row = del_rows
1831 delete_row = del_rows
1832 delete_rows = del_rows
1833
1834 def del_columns(
1835 self,
1836 columns: int | Iterator[int],
1837 data_indexes: bool = True,
1838 undo: bool = True,
1839 emit_event: bool = False,
1840 redraw: bool = True,
1841 ) -> EventDataDict:
1842 event_data = self.MT.delete_columns(
1843 columns=[columns] if isinstance(columns, int) else sorted(set(columns)),
1844 data_indexes=data_indexes,
1845 undo=undo,
1846 emit_event=emit_event,
1847 )
1848 self.set_refresh_timer(redraw)
1849 return event_data
1850
1851 del_column = del_columns
1852 delete_column = del_columns
1853 delete_columns = del_columns
1854
1855 def sheet_data_dimensions(
1856 self,
1857 total_rows: int | None = None,
1858 total_columns: int | None = None,
1859 ) -> Sheet:
1860 self.MT.data_dimensions(total_rows, total_columns)
1861 return self
1862
1863 def set_sheet_data_and_display_dimensions(
1864 self,
1865 total_rows: int | None = None,
1866 total_columns: int | None = None,
1867 ) -> Sheet:
1868 self.sheet_display_dimensions(total_rows=total_rows, total_columns=total_columns)
1869 self.MT.data_dimensions(total_rows=total_rows, total_columns=total_columns)
1870 return self
1871
1872 def total_rows(
1873 self,
1874 number: int | None = None,
1875 mod_positions: bool = True,
1876 mod_data: bool = True,
1877 ) -> int | Sheet:
1878 total_rows = self.MT.total_data_rows()
1879 if number is None:
1880 return total_rows
1881 if not isinstance(number, int) or number < 0:
1882 raise ValueError("number argument must be integer and > 0")
1883 if number > total_rows and mod_positions:
1884 self.MT.insert_row_positions(heights=number - total_rows)
1885 elif number < total_rows:
1886 if not self.MT.all_rows_displayed:
1887 self.MT.display_rows(enable=False, reset_row_positions=False, deselect_all=True)
1888 self.MT.row_positions[number + 1 :] = []
1889 if mod_data:
1890 self.MT.data_dimensions(total_rows=number)
1891 return self
1892
1893 def total_columns(
1894 self,
1895 number: int | None = None,
1896 mod_positions: bool = True,
1897 mod_data: bool = True,
1898 ) -> int | Sheet:
1899 total_cols = self.MT.total_data_cols()
1900 if number is None:
1901 return total_cols
1902 if not isinstance(number, int) or number < 0:
1903 raise ValueError("number argument must be integer and > 0")
1904 if number > total_cols and mod_positions:
1905 self.MT.insert_col_positions(widths=number - total_cols)
1906 elif number < total_cols:
1907 if not self.MT.all_columns_displayed:
1908 self.MT.display_columns(enable=False, reset_col_positions=False, deselect_all=True)
1909 self.MT.col_positions[number + 1 :] = []
1910 if mod_data:
1911 self.MT.data_dimensions(total_columns=number)
1912 return self
1913
1914 def move_row(self, row: int, moveto: int) -> tuple[dict[int, int], dict[int, int], EventDataDict]:
1915 return self.move_rows(moveto, [row])
1916
1917 def move_column(self, column: int, moveto: int) -> tuple[dict[int, int], dict[int, int], EventDataDict]:
1918 return self.move_columns(moveto, [column])
1919
1920 def move_rows(
1921 self,
1922 move_to: int | None = None,
1923 to_move: list[int] | None = None,
1924 move_data: bool = True,
1925 data_indexes: bool = False,
1926 create_selections: bool = True,
1927 undo: bool = True,
1928 emit_event: bool = False,
1929 move_heights: bool = True,
1930 event_data: EventDataDict | None = None,
1931 redraw: bool = True,
1932 ) -> tuple[dict[int, int], dict[int, int], EventDataDict]:
1933 if not event_data:
1934 event_data = self.MT.new_event_dict("move_rows", state=True)
1935 if not data_indexes:
1936 event_data.value = move_to
1937 data_idxs, disp_idxs, event_data = self.MT.move_rows_adjust_options_dict(
1938 *self.MT.get_args_for_move_rows(
1939 move_to=move_to,
1940 to_move=to_move,
1941 data_indexes=data_indexes,
1942 ),
1943 move_data=move_data,
1944 move_heights=move_heights,
1945 create_selections=create_selections,
1946 event_data=event_data,
1947 )
1948 if undo:
1949 self.MT.undo_stack.append(stored_event_dict(event_data))
1950 if emit_event:
1951 self.emit_event("<<SheetModified>>", event_data)
1952 self.set_refresh_timer(redraw)
1953 return data_idxs, disp_idxs, event_data
1954
1955 def move_columns(
1956 self,
1957 move_to: int | None = None,
1958 to_move: list[int] | None = None,
1959 move_data: bool = True,
1960 data_indexes: bool = False,
1961 create_selections: bool = True,
1962 undo: bool = True,
1963 emit_event: bool = False,
1964 move_widths: bool = True,
1965 event_data: EventDataDict | None = None,
1966 redraw: bool = True,
1967 ) -> tuple[dict[int, int], dict[int, int], EventDataDict]:
1968 if not event_data:
1969 event_data = self.MT.new_event_dict("move_columns", state=True)
1970 if not data_indexes:
1971 event_data.value = move_to
1972 data_idxs, disp_idxs, event_data = self.MT.move_columns_adjust_options_dict(
1973 *self.MT.get_args_for_move_columns(
1974 move_to=move_to,
1975 to_move=to_move,
1976 data_indexes=data_indexes,
1977 ),
1978 move_data=move_data,
1979 move_widths=move_widths,
1980 create_selections=create_selections,
1981 event_data=event_data,
1982 )
1983 if undo:
1984 self.MT.undo_stack.append(stored_event_dict(event_data))
1985 if emit_event:
1986 self.emit_event("<<SheetModified>>", event_data)
1987 self.set_refresh_timer(redraw)
1988 return data_idxs, disp_idxs, event_data
1989
1990 def mapping_move_columns(
1991 self,
1992 data_new_idxs: dict[int, int],
1993 disp_new_idxs: None | dict[int, int] = None,
1994 move_data: bool = True,
1995 create_selections: bool = True,
1996 undo: bool = True,
1997 emit_event: bool = False,
1998 redraw: bool = True,
1999 ) -> tuple[dict[int, int], dict[int, int], EventDataDict]:
2000 data_idxs, disp_idxs, event_data = self.MT.move_columns_adjust_options_dict(
2001 data_new_idxs=data_new_idxs,
2002 data_old_idxs=dict(zip(data_new_idxs.values(), data_new_idxs)),
2003 totalcols=None,
2004 disp_new_idxs=disp_new_idxs,
2005 move_data=move_data,
2006 create_selections=create_selections,
2007 )
2008 if undo:
2009 self.MT.undo_stack.append(stored_event_dict(event_data))
2010 if emit_event:
2011 self.emit_event("<<SheetModified>>", event_data)
2012 self.set_refresh_timer(redraw)
2013 return data_idxs, disp_idxs, event_data
2014
2015 def mapping_move_rows(
2016 self,
2017 data_new_idxs: dict[int, int],
2018 disp_new_idxs: None | dict[int, int] = None,
2019 move_data: bool = True,
2020 create_selections: bool = True,
2021 undo: bool = True,
2022 emit_event: bool = False,
2023 event_data: EventDataDict | None = None,
2024 redraw: bool = True,
2025 ) -> tuple[dict[int, int], dict[int, int], EventDataDict]:
2026 data_idxs, disp_idxs, event_data = self.MT.move_rows_adjust_options_dict(
2027 data_new_idxs=data_new_idxs,
2028 data_old_idxs=dict(zip(data_new_idxs.values(), data_new_idxs)),
2029 totalrows=None,
2030 disp_new_idxs=disp_new_idxs,
2031 move_data=move_data,
2032 create_selections=create_selections,
2033 event_data=event_data,
2034 )
2035 if undo:
2036 self.MT.undo_stack.append(stored_event_dict(event_data))
2037 if emit_event:
2038 self.emit_event("<<SheetModified>>", event_data)
2039 self.set_refresh_timer(redraw)
2040 return data_idxs, disp_idxs, event_data
2041
2042 def equalize_data_row_lengths(
2043 self,
2044 include_header: bool = True,
2045 ) -> int:
2046 return self.MT.equalize_data_row_lengths(
2047 include_header=include_header,
2048 )
2049
2050 def full_move_rows_idxs(self, data_idxs: dict[int, int], max_idx: int | None = None) -> dict[int, int]:
2051 """
2052 Converts the dict provided by moving rows event data
2053 Under the keys ['moved']['rows']['data']
2054 Into a dict of {old index: new index} for every row
2055 Includes row numbers in cell options, spans, etc.
2056 """
2057 return self.MT.get_full_new_idxs(
2058 self.MT.get_max_row_idx() if max_idx is None else max_idx,
2059 data_idxs,
2060 )
2061
2062 def full_move_columns_idxs(self, data_idxs: dict[int, int], max_idx: int | None = None) -> dict[int, int]:
2063 """
2064 Converts the dict provided by moving columns event data
2065 Under the keys ['moved']['columns']['data']
2066 Into a dict of {old index: new index} for every column
2067 Includes column numbers in cell options, spans, etc.
2068 """
2069 return self.MT.get_full_new_idxs(
2070 self.MT.get_max_column_idx() if max_idx is None else max_idx,
2071 data_idxs,
2072 )
2073
2074 # Sorting
2075
2076 def sort(
2077 self,
2078 *box: CreateSpanTypes,
2079 reverse: bool = False,
2080 row_wise: bool = False,
2081 validation: bool = True,
2082 key: Callable | None = None,
2083 undo: bool = True,
2084 ) -> EventDataDict:
2085 """
2086 Sort the data within specified box regions in the table.
2087
2088 This method sorts the data within one or multiple box regions defined by their coordinates.
2089 Each box's columns are sorted independently.
2090
2091 Args:
2092 boxes (CreateSpanTypes): A type that can create a Span.
2093
2094 reverse (bool): If True, sorts in descending order. Default is False (ascending).
2095
2096 row_wise (bool): if True sorts cells row-wise. Default is column-wise.
2097
2098 validation (bool): If True, checks if the new cell values are valid according to any restrictions
2099 (e.g., dropdown validations) before applying the sort. Default is True.
2100
2101 key (Callable | None): A function to extract a comparison key from each element in the columns.
2102 If None, a natural sorting key will be used, which can handle most Python objects, including:
2103 - None, booleans, numbers (int, float), datetime objects, strings, and unknown types.
2104 Note: Performance might be slow with the natural sort for very large datasets.
2105
2106 Returns:
2107 EventDataDict: A dictionary containing information about the sorting event,
2108 including changes made to the table.
2109
2110 Raises:
2111 ValueError: If the input boxes are not in the expected format or if the data cannot be sorted.
2112
2113 Note:
2114 - If validation is enabled, any cell content that fails validation will not be updated.
2115 - Any cell options attached to cells will not be moved. Event data can be used to re-locate them.
2116 """
2117 return self.MT.sort_boxes(
2118 boxes={Box_nt(*self.span_from_key(*box).coords): "cells"},
2119 reverse=reverse,
2120 row_wise=row_wise,
2121 validation=validation,
2122 key=key,
2123 undo=undo,
2124 )
2125
2126 def sort_rows(
2127 self,
2128 rows: Iterator[int] | Span | int | None = None,
2129 reverse: bool = False,
2130 validation: bool = True,
2131 key: Callable | None = None,
2132 undo: bool = True,
2133 ) -> EventDataDict:
2134 if isinstance(rows, Span):
2135 rows = rows.rows
2136 elif isinstance(rows, int):
2137 rows = (rows,)
2138 return self.RI._sort_rows(rows=rows, reverse=reverse, validation=validation, key=key, undo=undo)
2139
2140 def sort_columns(
2141 self,
2142 columns: Iterator[int] | Span | int | None = None,
2143 reverse: bool = False,
2144 validation: bool = True,
2145 key: Callable | None = None,
2146 undo: bool = True,
2147 ) -> EventDataDict:
2148 if isinstance(columns, Span):
2149 columns = columns.columns
2150 elif isinstance(columns, int):
2151 columns = (columns,)
2152 return self.CH._sort_columns(columns=columns, reverse=reverse, validation=validation, key=key, undo=undo)
2153
2154 def sort_rows_by_column(
2155 self,
2156 column: int | None = None,
2157 reverse: bool = False,
2158 key: Callable | None = None,
2159 undo: bool = True,
2160 ) -> EventDataDict:
2161 return self.CH._sort_rows_by_column(column=column, reverse=reverse, key=key, undo=undo)
2162
2163 def sort_columns_by_row(
2164 self,
2165 row: int | None = None,
2166 reverse: bool = False,
2167 key: Callable | None = None,
2168 undo: bool = True,
2169 ) -> EventDataDict:
2170 return self.RI._sort_columns_by_row(row=row, reverse=reverse, key=key, undo=undo)
2171
2172 # Find and Replace
2173
2174 @property
2175 def find_open(self) -> bool:
2176 return self.MT.find_window.open
2177
2178 def open_find(self, focus: bool = False) -> Sheet:
2179 self.MT.open_find_window(focus=focus)
2180 return self
2181
2182 def close_find(self) -> Sheet:
2183 self.MT.close_find_window()
2184 return self
2185
2186 def next_match(self, within: bool | None = None, find: str | None = None) -> Sheet:
2187 self.MT.find_next(within=within, find=find)
2188 return self
2189
2190 def prev_match(self, within: bool | None = None, find: str | None = None) -> Sheet:
2191 self.MT.find_previous(within=within, find=find)
2192 return self
2193
2194 def replace_all(self, mapping: dict[str, str], within: bool = False) -> EventDataDict:
2195 event_data = self.MT.new_event_dict("edit_table", boxes=self.MT.get_boxes())
2196 if within:
2197 iterable = chain.from_iterable(
2198 (
2199 box_gen_coords(
2200 *box.coords,
2201 start_r=box.coords.from_r,
2202 start_c=box.coords.from_c,
2203 reverse=False,
2204 all_rows_displayed=self.MT.all_rows_displayed,
2205 all_cols_displayed=self.MT.all_columns_displayed,
2206 displayed_rows=self.MT.displayed_rows,
2207 displayed_cols=self.MT.displayed_columns,
2208 )
2209 for box in self.MT.selection_boxes.values()
2210 )
2211 )
2212 else:
2213 iterable = box_gen_coords(
2214 from_r=0,
2215 from_c=0,
2216 upto_r=self.MT.total_data_rows(include_index=False),
2217 upto_c=self.MT.total_data_cols(include_header=False),
2218 start_r=0,
2219 start_c=0,
2220 reverse=False,
2221 )
2222 for r, c in iterable:
2223 for find, replace in mapping.items():
2224 m = self.MT.find_match(find, r, c)
2225 if (
2226 m
2227 and not within
2228 or (
2229 within
2230 and (self.MT.all_rows_displayed or bisect_in(self.MT.displayed_rows, r))
2231 and (self.MT.all_columns_displayed or bisect_in(self.MT.displayed_columns, c))
2232 )
2233 ):
2234 current = f"{self.MT.get_cell_data(r, c, True)}"
2235 new = sub(escape(find), replacer(find, replace, current), current, flags=IGNORECASE)
2236 if not self.MT.edit_validation_func or (
2237 self.MT.edit_validation_func
2238 and (new := self.MT.edit_validation_func(mod_event_val(event_data, new, (r, c)))) is not None
2239 ):
2240 event_data = self.MT.event_data_set_cell(
2241 r,
2242 c,
2243 new,
2244 event_data,
2245 )
2246 event_data = self.MT.bulk_edit_validation(event_data)
2247 if event_data["cells"]["table"]:
2248 self.MT.refresh()
2249 if self.MT.undo_enabled:
2250 self.MT.undo_stack.append(stored_event_dict(event_data))
2251 try_binding(self.MT.extra_end_replace_all_func, event_data)
2252 self.MT.sheet_modified(event_data)
2253 self.emit_event("<<SheetModified>>", event_data)
2254 return event_data
2255
2256 # Highlighting Cells
2257
2258 def highlight(
2259 self,
2260 *key: CreateSpanTypes,
2261 bg: bool | None | str = False,
2262 fg: bool | None | str = False,
2263 end: bool | None = None,
2264 overwrite: bool = False,
2265 redraw: bool = True,
2266 ) -> Span:
2267 span = self.span_from_key(*key)
2268 if bg is False and fg is False and end is None:
2269 return span
2270 rows, cols = self.ranges_from_span(span)
2271 table, index, header = span.table, span.index, span.header
2272 if span.kind == "cell":
2273 if header:
2274 for c in cols:
2275 add_highlight(self.CH.cell_options, c, bg, fg, end, overwrite)
2276 for r in rows:
2277 if index:
2278 add_highlight(self.RI.cell_options, r, bg, fg, end, overwrite)
2279 if table:
2280 for c in cols:
2281 add_highlight(self.MT.cell_options, (r, c), bg, fg, end, overwrite)
2282 elif span.kind == "row":
2283 for r in rows:
2284 if index:
2285 add_highlight(self.RI.cell_options, r, bg, fg, end, overwrite)
2286 if table:
2287 add_highlight(self.MT.row_options, r, bg, fg, end, overwrite)
2288 elif span.kind == "column":
2289 for c in cols:
2290 if header:
2291 add_highlight(self.CH.cell_options, c, bg, fg, end, overwrite)
2292 if table:
2293 add_highlight(self.MT.col_options, c, bg, fg, end, overwrite)
2294 self.set_refresh_timer(redraw)
2295 return span
2296
2297 def dehighlight(
2298 self,
2299 *key: CreateSpanTypes,
2300 redraw: bool = True,
2301 ) -> Span:
2302 span = self.span_from_key(*key)
2303 self.del_options_using_span(span, "highlight")
2304 self.set_refresh_timer(redraw)
2305 return span
2306
2307 def dehighlight_all(
2308 self,
2309 cells: bool = True,
2310 rows: bool = True,
2311 columns: bool = True,
2312 header: bool = True,
2313 index: bool = True,
2314 redraw: bool = True,
2315 ) -> Sheet:
2316 if cells:
2317 del_from_options(self.MT.cell_options, "highlight")
2318 if rows:
2319 del_from_options(self.MT.row_options, "highlight")
2320 if columns:
2321 del_from_options(self.MT.col_options, "highlight")
2322 if index:
2323 del_from_options(self.RI.cell_options, "highlight")
2324 if header:
2325 del_from_options(self.CH.cell_options, "highlight")
2326 return self.set_refresh_timer(redraw)
2327
2328 # Dropdown Boxes
2329
2330 def dropdown(
2331 self,
2332 *key: CreateSpanTypes,
2333 values: list[Any] | None = None,
2334 edit_data: bool = True,
2335 set_values: dict[tuple[int, int], Any] | None = None,
2336 set_value: Any = None,
2337 state: Literal["normal", "readonly", "disabled"] = "normal",
2338 redraw: bool = True,
2339 selection_function: Callable | None = None,
2340 modified_function: Callable | None = None,
2341 search_function: Callable | None = None,
2342 validate_input: bool = True,
2343 text: None | str = None,
2344 ) -> Span:
2345 if values is None:
2346 values = []
2347 if set_values is None:
2348 set_values = {}
2349 if not search_function:
2350 search_function = dropdown_search_function
2351 v = set_value if set_value is not None else values[0] if values else ""
2352 kwargs = {
2353 "values": values,
2354 "state": state,
2355 "selection_function": selection_function,
2356 "modified_function": modified_function,
2357 "search_function": search_function,
2358 "validate_input": validate_input,
2359 "text": text,
2360 }
2361 d = get_dropdown_dict(**kwargs)
2362 span = self.span_from_key(*key)
2363 rows, cols = self.ranges_from_span(span)
2364 table, index, header = span.table, span.index, span.header
2365 set_tdata = self.MT.set_cell_data
2366 set_idata = self.RI.set_cell_data
2367 set_hdata = self.CH.set_cell_data
2368 if index:
2369 for r in rows:
2370 self.del_index_cell_options_dropdown_and_checkbox(r)
2371 add_to_options(self.RI.cell_options, r, "dropdown", d)
2372 if edit_data:
2373 set_idata(r, value=set_values.get(r, v))
2374 if header:
2375 for c in cols:
2376 self.del_header_cell_options_dropdown_and_checkbox(c)
2377 add_to_options(self.CH.cell_options, c, "dropdown", d)
2378 if edit_data:
2379 set_hdata(c, value=set_values.get(c, v))
2380 if table:
2381 if span.kind == "cell":
2382 for r in rows:
2383 for c in cols:
2384 self.del_cell_options_dropdown_and_checkbox(r, c)
2385 add_to_options(self.MT.cell_options, (r, c), "dropdown", d)
2386 if edit_data:
2387 set_tdata(r, c, value=set_values.get((r, c), v))
2388 elif span.kind == "row":
2389 for r in rows:
2390 self.del_row_options_dropdown_and_checkbox(r)
2391 add_to_options(self.MT.row_options, r, "dropdown", d)
2392 if edit_data:
2393 for c in cols:
2394 set_tdata(r, c, value=set_values.get((r, c), v))
2395 elif span.kind == "column":
2396 for c in cols:
2397 self.del_column_options_dropdown_and_checkbox(c)
2398 add_to_options(self.MT.col_options, c, "dropdown", d)
2399 if edit_data:
2400 for r in rows:
2401 set_tdata(r, c, value=set_values.get((r, c), v))
2402 self.set_refresh_timer(redraw)
2403 return span
2404
2405 def del_dropdown(
2406 self,
2407 *key: CreateSpanTypes,
2408 redraw: bool = True,
2409 ) -> Span:
2410 span = self.span_from_key(*key)
2411 if span.table:
2412 self.MT.hide_dropdown_window()
2413 if span.index:
2414 self.RI.hide_dropdown_window()
2415 if span.header:
2416 self.CH.hide_dropdown_window()
2417 self.del_options_using_span(span, "dropdown")
2418 self.set_refresh_timer(redraw)
2419 return span
2420
2421 def open_dropdown(self, r: int, c: int) -> Sheet:
2422 self.MT.open_dropdown_window(r, c)
2423 return self
2424
2425 def close_dropdown(self, r: int | None = None, c: int | None = None) -> Sheet:
2426 self.MT.close_dropdown_window(r, c)
2427 return self
2428
2429 def open_header_dropdown(self, c: int) -> Sheet:
2430 self.CH.open_dropdown_window(c)
2431 return self
2432
2433 def close_header_dropdown(self, c: int | None = None) -> Sheet:
2434 self.CH.close_dropdown_window(c)
2435 return self
2436
2437 def open_index_dropdown(self, r: int) -> Sheet:
2438 self.RI.open_dropdown_window(r)
2439 return self
2440
2441 def close_index_dropdown(self, r: int | None = None) -> Sheet:
2442 self.RI.close_dropdown_window(r)
2443 return self
2444
2445 # Check Boxes
2446
2447 def checkbox(
2448 self,
2449 *key: CreateSpanTypes,
2450 edit_data: bool = True,
2451 checked: bool | None = None,
2452 state: Literal["normal", "disabled"] = "normal",
2453 redraw: bool = True,
2454 check_function: Callable | None = None,
2455 text: str = "",
2456 ) -> Span:
2457 kwargs = {
2458 "state": state,
2459 "check_function": check_function,
2460 "text": text,
2461 }
2462 d = get_checkbox_dict(**kwargs)
2463 span = self.span_from_key(*key)
2464 rows, cols = self.ranges_from_span(span)
2465 table, index, header = span.table, span.index, span.header
2466 set_tdata = self.MT.set_cell_data
2467 set_idata = self.RI.set_cell_data
2468 set_hdata = self.CH.set_cell_data
2469 if index:
2470 for r in rows:
2471 self.del_index_cell_options_dropdown_and_checkbox(r)
2472 add_to_options(self.RI.cell_options, r, "checkbox", d)
2473 if edit_data:
2474 set_idata(r, checked if isinstance(checked, bool) else force_bool(self.RI.get_cell_data(r)))
2475 if header:
2476 for c in cols:
2477 self.del_header_cell_options_dropdown_and_checkbox(c)
2478 add_to_options(self.CH.cell_options, c, "checkbox", d)
2479 if edit_data:
2480 set_hdata(c, checked if isinstance(checked, bool) else force_bool(self.CH.get_cell_data(c)))
2481 if table:
2482 if span.kind == "cell":
2483 for r in rows:
2484 for c in cols:
2485 self.MT.delete_cell_format(r, c, clear_values=False)
2486 self.del_cell_options_dropdown_and_checkbox(r, c)
2487 add_to_options(self.MT.cell_options, (r, c), "checkbox", d)
2488 if edit_data:
2489 set_tdata(
2490 r, c, checked if isinstance(checked, bool) else force_bool(self.get_cell_data(r, c))
2491 )
2492 elif span.kind == "row":
2493 for r in rows:
2494 self.MT.delete_row_format(r, clear_values=False)
2495 self.del_row_options_dropdown_and_checkbox(r)
2496 add_to_options(self.MT.row_options, r, "checkbox", d)
2497 if edit_data:
2498 for c in cols:
2499 set_tdata(
2500 r, c, checked if isinstance(checked, bool) else force_bool(self.get_cell_data(r, c))
2501 )
2502 elif span.kind == "column":
2503 for c in cols:
2504 self.MT.delete_column_format(c, clear_values=False)
2505 self.del_column_options_dropdown_and_checkbox(c)
2506 add_to_options(self.MT.col_options, c, "checkbox", d)
2507 if edit_data:
2508 for r in rows:
2509 set_tdata(
2510 r, c, checked if isinstance(checked, bool) else force_bool(self.get_cell_data(r, c))
2511 )
2512 self.set_refresh_timer(redraw)
2513 return span
2514
2515 def del_checkbox(
2516 self,
2517 *key: CreateSpanTypes,
2518 redraw: bool = True,
2519 ) -> Span:
2520 span = self.span_from_key(*key)
2521 self.del_options_using_span(span, "checkbox")
2522 self.set_refresh_timer(redraw)
2523 return span
2524
2525 def click_checkbox(
2526 self,
2527 *key: CreateSpanTypes,
2528 checked: bool | None = None,
2529 redraw: bool = True,
2530 ) -> Span:
2531 span = self.span_from_key(*key)
2532 rows, cols = self.ranges_from_span(span)
2533 table, index, header = span.table, span.index, span.header
2534 set_tdata = self.MT.set_cell_data
2535 set_idata = self.RI.set_cell_data
2536 set_hdata = self.CH.set_cell_data
2537 get_tdata = self.MT.get_cell_data
2538 get_idata = self.RI.get_cell_data
2539 get_hdata = self.CH.get_cell_data
2540 get_tkw = self.MT.get_cell_kwargs
2541 get_ikw = self.RI.get_cell_kwargs
2542 get_hkw = self.CH.get_cell_kwargs
2543 if span.kind == "cell":
2544 if header:
2545 for c in cols:
2546 if get_hkw(c, key="checkbox"):
2547 set_hdata(c, not get_hdata(c) if checked is None else bool(checked))
2548 for r in rows:
2549 if index and get_ikw(r, key="checkbox"):
2550 set_idata(r, not get_idata(r) if checked is None else bool(checked))
2551 if table:
2552 for c in cols:
2553 if get_tkw(r, c, key="checkbox"):
2554 set_tdata(r, c, not get_tdata(r, c) if checked is None else bool(checked))
2555 elif span.kind == "row":
2556 totalcols = range(self.MT.total_data_cols())
2557 for r in rows:
2558 if index and get_ikw(r, key="checkbox"):
2559 set_idata(r, not get_idata(r) if checked is None else bool(checked))
2560 if table:
2561 for c in totalcols:
2562 if get_tkw(r, c, key="checkbox"):
2563 set_tdata(r, c, not get_tdata(r, c) if checked is None else bool(checked))
2564 elif span.kind == "column":
2565 totalrows = range(self.MT.total_data_rows())
2566 for c in cols:
2567 if header and get_hkw(c, key="checkbox"):
2568 set_hdata(c, not get_hdata(c) if checked is None else bool(checked))
2569 if table:
2570 for r in totalrows:
2571 if get_tkw(r, c, key="checkbox"):
2572 set_tdata(r, c, not get_tdata(r, c) if checked is None else bool(checked))
2573 self.set_refresh_timer(redraw)
2574 return span
2575
2576 # Data Formatting
2577
2578 def format(
2579 self,
2580 *key: CreateSpanTypes,
2581 formatter_options: dict | None = None,
2582 formatter_class: Any = None,
2583 redraw: bool = True,
2584 **kwargs,
2585 ) -> Span:
2586 if formatter_options is None:
2587 formatter_options = {}
2588 span = self.span_from_key(*key)
2589 rows, cols = self.ranges_from_span(span)
2590 kwargs = fix_format_kwargs({"formatter": formatter_class, **formatter_options, **kwargs})
2591 if span.kind == "cell" and span.table:
2592 for r in rows:
2593 for c in cols:
2594 self.del_cell_options_checkbox(r, c)
2595 add_to_options(self.MT.cell_options, (r, c), "format", kwargs)
2596 self.MT.set_cell_data(
2597 r,
2598 c,
2599 value=kwargs["value"] if "value" in kwargs else self.MT.get_cell_data(r, c),
2600 kwargs=kwargs,
2601 )
2602 elif span.kind == "row":
2603 for r in rows:
2604 self.del_row_options_checkbox(r)
2605 kwargs = fix_format_kwargs(kwargs)
2606 add_to_options(self.MT.row_options, r, "format", kwargs)
2607 for c in cols:
2608 self.MT.set_cell_data(
2609 r,
2610 c,
2611 value=kwargs["value"] if "value" in kwargs else self.MT.get_cell_data(r, c),
2612 kwargs=kwargs,
2613 )
2614 elif span.kind == "column":
2615 for c in cols:
2616 self.del_column_options_checkbox(c)
2617 kwargs = fix_format_kwargs(kwargs)
2618 add_to_options(self.MT.col_options, c, "format", kwargs)
2619 for r in rows:
2620 self.MT.set_cell_data(
2621 r,
2622 c,
2623 value=kwargs["value"] if "value" in kwargs else self.MT.get_cell_data(r, c),
2624 kwargs=kwargs,
2625 )
2626 self.set_refresh_timer(redraw)
2627 return span
2628
2629 def del_format(
2630 self,
2631 *key: CreateSpanTypes,
2632 clear_values: bool = False,
2633 redraw: bool = True,
2634 ) -> Span:
2635 span = self.span_from_key(*key)
2636 rows, cols = self.ranges_from_span(span)
2637 if span.table:
2638 if span.kind == "cell":
2639 for r in rows:
2640 for c in cols:
2641 self.MT.delete_cell_format(r, c, clear_values=clear_values)
2642 elif span.kind == "row":
2643 for r in rows:
2644 self.MT.delete_row_format(r, clear_values=clear_values)
2645 elif span.kind == "column":
2646 for c in cols:
2647 self.MT.delete_column_format(c, clear_values=clear_values)
2648 self.set_refresh_timer(redraw)
2649 return span
2650
2651 def reapply_formatting(self) -> Sheet:
2652 self.MT.reapply_formatting()
2653 return self
2654
2655 def del_all_formatting(self, clear_values: bool = False) -> Sheet:
2656 self.MT.delete_all_formatting(clear_values=clear_values)
2657 return self
2658
2659 delete_all_formatting = del_all_formatting
2660
2661 def formatted(self, r: int, c: int) -> dict:
2662 return self.MT.get_cell_kwargs(r, c, key="format")
2663
2664 # Readonly Cells
2665
2666 def readonly(
2667 self,
2668 *key: CreateSpanTypes,
2669 readonly: bool = True,
2670 ) -> Span:
2671 span = self.span_from_key(*key)
2672 rows, cols = self.ranges_from_span(span)
2673 table, index, header = span.table, span.index, span.header
2674 if span.kind == "cell":
2675 if header:
2676 for c in cols:
2677 set_readonly(self.CH.cell_options, c, readonly)
2678 for r in rows:
2679 if index:
2680 set_readonly(self.RI.cell_options, r, readonly)
2681 if table:
2682 for c in cols:
2683 set_readonly(self.MT.cell_options, (r, c), readonly)
2684 elif span.kind == "row":
2685 for r in rows:
2686 if index:
2687 set_readonly(self.RI.cell_options, r, readonly)
2688 if table:
2689 set_readonly(self.MT.row_options, r, readonly)
2690 elif span.kind == "column":
2691 for c in cols:
2692 if header:
2693 set_readonly(self.CH.cell_options, c, readonly)
2694 if table:
2695 set_readonly(self.MT.col_options, c, readonly)
2696 return span
2697
2698 # Text Font and Alignment
2699
2700 def font(self, newfont: tuple[str, int, str] | None = None, **_) -> tuple[str, int, str]:
2701 return self.MT.set_table_font(newfont)
2702
2703 table_font = font
2704
2705 def header_font(self, newfont: tuple[str, int, str] | None = None) -> tuple[str, int, str]:
2706 return self.MT.set_header_font(newfont)
2707
2708 def index_font(self, newfont: tuple[str, int, str] | None = None) -> tuple[str, int, str]:
2709 return self.MT.set_index_font(newfont)
2710
2711 def table_align(
2712 self,
2713 align: str | None = None,
2714 redraw: bool = True,
2715 ) -> str | Sheet:
2716 if align is None:
2717 return self.MT.align
2718 elif convert_align(align):
2719 self.MT.align = convert_align(align)
2720 else:
2721 raise ValueError()
2722 return self.set_refresh_timer(redraw)
2723
2724 def header_align(
2725 self,
2726 align: str | None = None,
2727 redraw: bool = True,
2728 ) -> str | Sheet:
2729 if align is None:
2730 return self.CH.align
2731 elif convert_align(align):
2732 self.CH.align = convert_align(align)
2733 else:
2734 raise ValueError(align_value_error)
2735 return self.set_refresh_timer(redraw)
2736
2737 def row_index_align(
2738 self,
2739 align: str | None = None,
2740 redraw: bool = True,
2741 ) -> str | Sheet:
2742 if align is None:
2743 return self.RI.align
2744 elif convert_align(align):
2745 self.RI.align = convert_align(align)
2746 else:
2747 raise ValueError(align_value_error)
2748 return self.set_refresh_timer(redraw)
2749
2750 index_align = row_index_align
2751
2752 def align(
2753 self,
2754 *key: CreateSpanTypes,
2755 align: str | None = None,
2756 redraw: bool = True,
2757 ) -> Span:
2758 span = self.span_from_key(*key)
2759 rows, cols = self.ranges_from_span(span)
2760 table, index, header = span.table, span.index, span.header
2761 align = convert_align(align)
2762 if span.kind == "cell":
2763 if header:
2764 for c in cols:
2765 set_align(self.CH.cell_options, c, align)
2766 for r in rows:
2767 if index:
2768 set_align(self.RI.cell_options, r, align)
2769 if table:
2770 for c in cols:
2771 set_align(self.MT.cell_options, (r, c), align)
2772 elif span.kind == "row":
2773 for r in rows:
2774 if index:
2775 set_align(self.RI.cell_options, r, align)
2776 if table:
2777 set_align(self.MT.row_options, r, align)
2778 elif span.kind == "column":
2779 for c in cols:
2780 if header:
2781 set_align(self.CH.cell_options, c, align)
2782 if table:
2783 set_align(self.MT.col_options, c, align)
2784 self.set_refresh_timer(redraw)
2785 return span
2786
2787 def del_align(
2788 self,
2789 *key: CreateSpanTypes,
2790 redraw: bool = True,
2791 ) -> Span:
2792 span = self.span_from_key(*key)
2793 self.del_options_using_span(span, "align")
2794 self.set_refresh_timer(redraw)
2795 return span
2796
2797 # Getting Selected Cells
2798
2799 def get_currently_selected(self) -> tuple[()] | Selected:
2800 # if self.MT.selected:
2801 # return self.MT.selected._replace(type_=self.MT.selected.type_[:-1])
2802 return self.MT.selected
2803
2804 @property
2805 def selected(self) -> tuple[()] | Selected:
2806 return self.MT.selected
2807
2808 @selected.setter
2809 def selected(self, selected: tuple[()] | Selected) -> Sheet:
2810 if selected:
2811 self.MT.set_currently_selected(
2812 r=selected[0],
2813 c=selected[1],
2814 item=selected[4],
2815 box=selected[3],
2816 )
2817 else:
2818 self.MT.deselect(redraw=False)
2819 return self.set_refresh_timer()
2820
2821 def get_selected_rows(
2822 self,
2823 get_cells: bool = False,
2824 get_cells_as_rows: bool = False,
2825 return_tuple: bool = False,
2826 ) -> tuple[int] | tuple[tuple[int, int]] | set[int] | set[tuple[int, int]]:
2827 if return_tuple:
2828 return tuple(self.MT.get_selected_rows(get_cells=get_cells, get_cells_as_rows=get_cells_as_rows))
2829 return self.MT.get_selected_rows(get_cells=get_cells, get_cells_as_rows=get_cells_as_rows)
2830
2831 def get_selected_columns(
2832 self,
2833 get_cells: bool = False,
2834 get_cells_as_columns: bool = False,
2835 return_tuple: bool = False,
2836 ) -> tuple[int] | tuple[tuple[int, int]] | set[int] | set[tuple[int, int]]:
2837 if return_tuple:
2838 return tuple(self.MT.get_selected_cols(get_cells=get_cells, get_cells_as_cols=get_cells_as_columns))
2839 return self.MT.get_selected_cols(get_cells=get_cells, get_cells_as_cols=get_cells_as_columns)
2840
2841 def get_selected_cells(
2842 self,
2843 get_rows: bool = False,
2844 get_columns: bool = False,
2845 sort_by_row: bool = False,
2846 sort_by_column: bool = False,
2847 reverse: bool = False,
2848 ) -> list[tuple[int, int]] | set[tuple[int, int]]:
2849 if sort_by_row and sort_by_column:
2850 return sorted(
2851 self.MT.get_selected_cells(get_rows=get_rows, get_cols=get_columns),
2852 key=lambda t: t,
2853 reverse=reverse,
2854 )
2855 elif sort_by_row:
2856 return sorted(
2857 self.MT.get_selected_cells(get_rows=get_rows, get_cols=get_columns),
2858 key=lambda t: t[0],
2859 reverse=reverse,
2860 )
2861 elif sort_by_column:
2862 return sorted(
2863 self.MT.get_selected_cells(get_rows=get_rows, get_cols=get_columns),
2864 key=lambda t: t[1],
2865 reverse=reverse,
2866 )
2867 return self.MT.get_selected_cells(get_rows=get_rows, get_cols=get_columns)
2868
2869 def gen_selected_cells(
2870 self,
2871 get_rows: bool = False,
2872 get_columns: bool = False,
2873 ) -> Generator[tuple[int, int]]:
2874 yield from self.MT.gen_selected_cells(get_rows=get_rows, get_cols=get_columns)
2875
2876 def get_all_selection_boxes(self) -> tuple[tuple[int, int, int, int]]:
2877 return self.MT.get_all_selection_boxes()
2878
2879 def get_all_selection_boxes_with_types(self) -> list[tuple[tuple[int, int, int, int], str]]:
2880 return self.MT.get_all_selection_boxes_with_types()
2881
2882 @property
2883 def boxes(self) -> list[tuple[tuple[int, int, int, int], str]]:
2884 return self.MT.get_all_selection_boxes_with_types()
2885
2886 @boxes.setter
2887 def boxes(self, boxes: Sequence[tuple[tuple[int, int, int, int], str]]) -> Sheet:
2888 self.MT.deselect(redraw=False)
2889 self.MT.reselect_from_get_boxes(
2890 boxes={box[0] if isinstance(box[0], tuple) else tuple(box[0]): box[1] for box in boxes}
2891 )
2892 return self.set_refresh_timer()
2893
2894 @property
2895 def canvas_boxes(self) -> dict[int, SelectionBox]:
2896 return self.MT.selection_boxes
2897
2898 def cell_selected(
2899 self,
2900 r: int,
2901 c: int,
2902 rows: bool = False,
2903 columns: bool = False,
2904 ) -> bool:
2905 return self.MT.cell_selected(r, c, inc_cols=columns, inc_rows=rows)
2906
2907 def row_selected(self, r: int, cells: bool = False) -> bool:
2908 return self.MT.row_selected(r, cells=cells)
2909
2910 def column_selected(self, c: int, cells: bool = False) -> bool:
2911 return self.MT.col_selected(c, cells=cells)
2912
2913 def anything_selected(
2914 self,
2915 exclude_columns: bool = False,
2916 exclude_rows: bool = False,
2917 exclude_cells: bool = False,
2918 ) -> bool:
2919 return bool(
2920 self.MT.anything_selected(
2921 exclude_columns=exclude_columns,
2922 exclude_rows=exclude_rows,
2923 exclude_cells=exclude_cells,
2924 )
2925 )
2926
2927 def all_selected(self) -> bool:
2928 return self.MT.all_selected()
2929
2930 def get_ctrl_x_c_boxes(
2931 self,
2932 nrows: bool = True,
2933 ) -> tuple[dict[tuple[int, int, int, int], str], int] | dict[tuple[int, int, int, int], str]:
2934 if nrows:
2935 return self.MT.get_ctrl_x_c_boxes()
2936 return self.MT.get_ctrl_x_c_boxes()[0]
2937
2938 @property
2939 def ctrl_boxes(self) -> dict[tuple[int, int, int, int], str]:
2940 return self.MT.get_ctrl_x_c_boxes()[0]
2941
2942 def get_selected_min_max(
2943 self,
2944 ) -> tuple[int, int, int, int] | tuple[None, None, None, None]:
2945 """
2946 Returns (min_y, min_x, max_y, max_x) of all selection boxes
2947 """
2948 return self.MT.get_selected_min_max()
2949
2950 # Modifying Selected Cells
2951
2952 def set_currently_selected(self, row: int | None = None, column: int | None = None, **kwargs) -> Sheet:
2953 self.MT.set_currently_selected(
2954 r=row,
2955 c=column,
2956 **kwargs,
2957 )
2958 return self
2959
2960 def select_row(self, row: int, redraw: bool = True, run_binding_func: bool = True) -> Sheet:
2961 self.RI.select_row(
2962 row if isinstance(row, int) else int(row),
2963 redraw=False,
2964 run_binding_func=run_binding_func,
2965 ext=True,
2966 )
2967 return self.set_refresh_timer(redraw)
2968
2969 def select_column(self, column: int, redraw: bool = True, run_binding_func: bool = True) -> Sheet:
2970 self.CH.select_col(
2971 column if isinstance(column, int) else int(column),
2972 redraw=False,
2973 run_binding_func=run_binding_func,
2974 ext=True,
2975 )
2976 return self.set_refresh_timer(redraw)
2977
2978 def select_cell(self, row: int, column: int, redraw: bool = True, run_binding_func: bool = True) -> Sheet:
2979 self.MT.select_cell(
2980 row if isinstance(row, int) else int(row),
2981 column if isinstance(column, int) else int(column),
2982 redraw=False,
2983 run_binding_func=run_binding_func,
2984 ext=True,
2985 )
2986 return self.set_refresh_timer(redraw)
2987
2988 def select_all(self, redraw: bool = True, run_binding_func: bool = True) -> Sheet:
2989 self.MT.select_all(redraw=False, run_binding_func=run_binding_func)
2990 return self.set_refresh_timer(redraw)
2991
2992 def add_cell_selection(
2993 self,
2994 row: int,
2995 column: int,
2996 redraw: bool = True,
2997 run_binding_func: bool = True,
2998 set_as_current: bool = True,
2999 ) -> Sheet:
3000 self.MT.add_selection(
3001 r=row,
3002 c=column,
3003 redraw=False,
3004 run_binding_func=run_binding_func,
3005 set_as_current=set_as_current,
3006 ext=True,
3007 )
3008 return self.set_refresh_timer(redraw)
3009
3010 def add_row_selection(
3011 self,
3012 row: int,
3013 redraw: bool = True,
3014 run_binding_func: bool = True,
3015 set_as_current: bool = True,
3016 ) -> Sheet:
3017 self.RI.add_selection(
3018 r=row,
3019 redraw=False,
3020 run_binding_func=run_binding_func,
3021 set_as_current=set_as_current,
3022 ext=True,
3023 )
3024 return self.set_refresh_timer(redraw)
3025
3026 def add_column_selection(
3027 self,
3028 column: int,
3029 redraw: bool = True,
3030 run_binding_func: bool = True,
3031 set_as_current: bool = True,
3032 ) -> Sheet:
3033 self.CH.add_selection(
3034 c=column,
3035 redraw=False,
3036 run_binding_func=run_binding_func,
3037 set_as_current=set_as_current,
3038 ext=True,
3039 )
3040 return self.set_refresh_timer(redraw)
3041
3042 def toggle_select_cell(
3043 self,
3044 row: int,
3045 column: int,
3046 add_selection: bool = True,
3047 redraw: bool = True,
3048 run_binding_func: bool = True,
3049 set_as_current: bool = True,
3050 ) -> Sheet:
3051 self.MT.toggle_select_cell(
3052 row=row,
3053 column=column,
3054 add_selection=add_selection,
3055 redraw=False,
3056 run_binding_func=run_binding_func,
3057 set_as_current=set_as_current,
3058 ext=True,
3059 )
3060 return self.set_refresh_timer(redraw)
3061
3062 def toggle_select_row(
3063 self,
3064 row: int,
3065 add_selection: bool = True,
3066 redraw: bool = True,
3067 run_binding_func: bool = True,
3068 set_as_current: bool = True,
3069 ) -> Sheet:
3070 self.RI.toggle_select_row(
3071 row=row,
3072 add_selection=add_selection,
3073 redraw=False,
3074 run_binding_func=run_binding_func,
3075 set_as_current=set_as_current,
3076 ext=True,
3077 )
3078 return self.set_refresh_timer(redraw)
3079
3080 def toggle_select_column(
3081 self,
3082 column: int,
3083 add_selection: bool = True,
3084 redraw: bool = True,
3085 run_binding_func: bool = True,
3086 set_as_current: bool = True,
3087 ) -> Sheet:
3088 self.CH.toggle_select_col(
3089 column=column,
3090 add_selection=add_selection,
3091 redraw=False,
3092 run_binding_func=run_binding_func,
3093 set_as_current=set_as_current,
3094 ext=True,
3095 )
3096 return self.set_refresh_timer(redraw)
3097
3098 def create_selection_box(
3099 self,
3100 r1: int,
3101 c1: int,
3102 r2: int,
3103 c2: int,
3104 type_: Literal["cells", "rows", "columns", "cols"] = "cells",
3105 ) -> int:
3106 return self.MT.create_selection_box(
3107 r1=r1,
3108 c1=c1,
3109 r2=r2,
3110 c2=c2,
3111 type_="columns" if type_ == "cols" else type_,
3112 ext=True,
3113 )
3114
3115 def recreate_all_selection_boxes(self) -> Sheet:
3116 self.MT.recreate_all_selection_boxes()
3117 return self
3118
3119 def deselect(
3120 self,
3121 row: int | None | Literal["all"] = None,
3122 column: int | None = None,
3123 cell: tuple[int, int] | None = None,
3124 redraw: bool = True,
3125 ) -> Sheet:
3126 self.MT.deselect(r=row, c=column, cell=cell, redraw=False)
3127 return self.set_refresh_timer(redraw)
3128
3129 def deselect_any(
3130 self,
3131 rows: Iterator[int] | int | None,
3132 columns: Iterator[int] | int | None,
3133 redraw: bool = True,
3134 ) -> Sheet:
3135 self.MT.deselect_any(rows=rows, columns=columns, redraw=False)
3136 return self.set_refresh_timer(redraw)
3137
3138 # Row Heights and Column Widths
3139
3140 def default_column_width(self, width: int | None = None) -> int:
3141 if isinstance(width, int):
3142 self.ops.default_column_width = width
3143 return self.ops.default_column_width
3144
3145 def default_row_height(self, height: int | str | None = None) -> int:
3146 if isinstance(height, (int, str)):
3147 self.ops.default_row_height = height
3148 return self.ops.default_row_height
3149
3150 def default_header_height(self, height: int | str | None = None) -> int:
3151 if isinstance(height, (int, str)):
3152 self.ops.default_header_height = height
3153 return self.ops.default_header_height
3154
3155 def set_cell_size_to_text(
3156 self,
3157 row: int,
3158 column: int,
3159 only_set_if_too_small: bool = False,
3160 redraw: bool = True,
3161 ) -> Sheet:
3162 self.MT.set_cell_size_to_text(r=row, c=column, only_if_too_small=only_set_if_too_small)
3163 return self.set_refresh_timer(redraw)
3164
3165 def set_all_cell_sizes_to_text(
3166 self,
3167 redraw: bool = True,
3168 width: int | None = None,
3169 slim: bool = False,
3170 ) -> tuple[list[float], list[float]]:
3171 self.MT.set_all_cell_sizes_to_text(width=width, slim=slim)
3172 self.set_refresh_timer(redraw)
3173 return self.MT.row_positions, self.MT.col_positions
3174
3175 def set_all_column_widths(
3176 self,
3177 width: int | None = None,
3178 only_set_if_too_small: bool = False,
3179 redraw: bool = True,
3180 recreate_selection_boxes: bool = True,
3181 ) -> Sheet:
3182 self.CH.set_width_of_all_cols(
3183 width=width,
3184 only_if_too_small=only_set_if_too_small,
3185 recreate=recreate_selection_boxes,
3186 )
3187 return self.set_refresh_timer(redraw)
3188
3189 def set_all_row_heights(
3190 self,
3191 height: int | None = None,
3192 only_set_if_too_small: bool = False,
3193 redraw: bool = True,
3194 recreate_selection_boxes: bool = True,
3195 ) -> Sheet:
3196 self.RI.set_height_of_all_rows(
3197 height=height,
3198 only_if_too_small=only_set_if_too_small,
3199 recreate=recreate_selection_boxes,
3200 )
3201 return self.set_refresh_timer(redraw)
3202
3203 def column_width(
3204 self,
3205 column: int | Literal["all", "displayed"] | None = None,
3206 width: int | Literal["default", "text"] | None = None,
3207 only_set_if_too_small: bool = False,
3208 redraw: bool = True,
3209 ) -> Sheet | int:
3210 if column == "all":
3211 if width == "default":
3212 self.MT.reset_col_positions()
3213 elif width == "text":
3214 self.set_all_column_widths(only_set_if_too_small=only_set_if_too_small)
3215 elif isinstance(width, int):
3216 self.MT.reset_col_positions(width=width)
3217
3218 elif column == "displayed":
3219 if width == "default":
3220 for c in range(*self.MT.visible_text_columns):
3221 self.CH.set_col_width(
3222 c, width=self.ops.default_column_width, only_if_too_small=only_set_if_too_small
3223 )
3224 elif width == "text":
3225 for c in range(*self.MT.visible_text_columns):
3226 self.CH.set_col_width(c, only_if_too_small=only_set_if_too_small)
3227 elif isinstance(width, int):
3228 for c in range(*self.MT.visible_text_columns):
3229 self.CH.set_col_width(c, width=width, only_if_too_small=only_set_if_too_small)
3230
3231 elif isinstance(column, int):
3232 if width == "default":
3233 self.CH.set_col_width(
3234 col=column, width=self.ops.default_column_width, only_if_too_small=only_set_if_too_small
3235 )
3236 elif width == "text":
3237 self.CH.set_col_width(col=column, only_if_too_small=only_set_if_too_small)
3238 elif isinstance(width, int):
3239 self.CH.set_col_width(col=column, width=width, only_if_too_small=only_set_if_too_small)
3240 elif width is None:
3241 return int(self.MT.col_positions[column + 1] - self.MT.col_positions[column])
3242
3243 else:
3244 return self.set_refresh_timer(redraw)
3245
3246 def row_height(
3247 self,
3248 row: int | Literal["all", "displayed"] | None = None,
3249 height: int | Literal["default", "text"] | None = None,
3250 only_set_if_too_small: bool = False,
3251 redraw: bool = True,
3252 ) -> Sheet | int:
3253 if row == "all":
3254 if height == "default":
3255 self.MT.reset_row_positions()
3256 elif height == "text":
3257 self.set_all_row_heights()
3258 elif isinstance(height, int):
3259 self.MT.reset_row_positions(height=height)
3260
3261 elif row == "displayed":
3262 if height == "default":
3263 height = self.MT.get_default_row_height()
3264 for r in range(*self.MT.visible_text_rows):
3265 self.RI.set_row_height(r, height=height, only_if_too_small=only_set_if_too_small)
3266 elif height == "text":
3267 for r in range(*self.MT.visible_text_rows):
3268 self.RI.set_row_height(r, only_if_too_small=only_set_if_too_small)
3269 elif isinstance(height, int):
3270 for r in range(*self.MT.visible_text_rows):
3271 self.RI.set_row_height(r, height=height, only_if_too_small=only_set_if_too_small)
3272
3273 elif isinstance(row, int):
3274 if height == "default":
3275 height = self.MT.get_default_row_height()
3276 self.RI.set_row_height(row=row, height=height, only_if_too_small=only_set_if_too_small)
3277 elif height == "text":
3278 self.RI.set_row_height(row=row, only_if_too_small=only_set_if_too_small)
3279 elif isinstance(height, int):
3280 self.RI.set_row_height(row=row, height=height, only_if_too_small=only_set_if_too_small)
3281 elif height is None:
3282 return int(self.MT.row_positions[row + 1] - self.MT.row_positions[row])
3283
3284 else:
3285 return self.set_refresh_timer(redraw)
3286
3287 def get_column_widths(self, canvas_positions: bool = False) -> list[float]:
3288 if canvas_positions:
3289 return self.MT.col_positions
3290 return self.MT.get_column_widths()
3291
3292 def get_row_heights(self, canvas_positions: bool = False) -> list[float]:
3293 if canvas_positions:
3294 return self.MT.row_positions
3295 return self.MT.get_row_heights()
3296
3297 def get_safe_row_heights(self) -> list[int]:
3298 default_h = self.MT.get_default_row_height()
3299 return [0 if e == default_h else e for e in self.MT.gen_row_heights()]
3300
3301 def set_safe_row_heights(self, heights: list[int]) -> Sheet:
3302 default_h = self.MT.get_default_row_height()
3303 self.MT.row_positions = list(
3304 accumulate(chain([0], (self.valid_row_height(e) if e else default_h for e in heights)))
3305 )
3306 return self
3307
3308 def get_row_text_height(
3309 self,
3310 row: int,
3311 visible_only: bool = False,
3312 only_if_too_small: bool = False,
3313 ) -> int:
3314 return self.RI.get_row_text_height(
3315 row=row,
3316 visible_only=visible_only,
3317 only_if_too_small=only_if_too_small,
3318 )
3319
3320 def get_column_text_width(
3321 self,
3322 column: int,
3323 visible_only: bool = False,
3324 only_if_too_small: bool = False,
3325 ) -> int:
3326 return self.CH.get_col_text_width(
3327 col=column,
3328 visible_only=visible_only,
3329 only_if_too_small=only_if_too_small,
3330 )
3331
3332 def set_column_widths(
3333 self,
3334 column_widths: Iterator[float] | None = None,
3335 canvas_positions: bool = False,
3336 reset: bool = False,
3337 ) -> Sheet:
3338 if reset or column_widths is None:
3339 self.MT.reset_col_positions()
3340 elif is_iterable(column_widths):
3341 if canvas_positions and isinstance(column_widths, list):
3342 self.MT.col_positions = column_widths
3343 else:
3344 self.MT.col_positions = list(accumulate(chain([0], column_widths)))
3345 return self
3346
3347 def set_row_heights(
3348 self,
3349 row_heights: Iterator[float] | None = None,
3350 canvas_positions: bool = False,
3351 reset: bool = False,
3352 ) -> Sheet:
3353 if reset or row_heights is None:
3354 self.MT.reset_row_positions()
3355 elif is_iterable(row_heights):
3356 if canvas_positions and isinstance(row_heights, list):
3357 self.MT.row_positions = row_heights
3358 else:
3359 self.MT.row_positions = list(accumulate(chain([0], row_heights)))
3360 return self
3361
3362 def set_width_of_index_to_text(self, text: None | str = None, *args, **kwargs) -> Sheet:
3363 self.RI.set_width_of_index_to_text(text=text)
3364 return self
3365
3366 def set_index_width(self, pixels: int, redraw: bool = True) -> Sheet:
3367 if self.ops.auto_resize_row_index:
3368 self.ops.auto_resize_row_index = False
3369 self.RI.set_width(pixels, set_TL=True)
3370 return self.set_refresh_timer(redraw)
3371
3372 def set_height_of_header_to_text(self, text: None | str = None) -> Sheet:
3373 self.CH.set_height_of_header_to_text(text=text)
3374 return self
3375
3376 def set_header_height_pixels(self, pixels: int, redraw: bool = True) -> Sheet:
3377 self.CH.set_height(pixels, set_TL=True)
3378 return self.set_refresh_timer(redraw)
3379
3380 def set_header_height_lines(self, nlines: int, redraw: bool = True) -> Sheet:
3381 self.CH.set_height(
3382 self.MT.get_lines_cell_height(
3383 nlines,
3384 font=self.ops.header_font,
3385 ),
3386 set_TL=True,
3387 )
3388 return self.set_refresh_timer(redraw)
3389
3390 def del_row_position(self, idx: int, deselect_all: bool = False) -> Sheet:
3391 self.MT.del_row_position(idx=idx, deselect_all=deselect_all)
3392 return self
3393
3394 delete_row_position = del_row_position
3395
3396 def del_row_positions(self, idxs: Iterator[int] | None = None) -> Sheet:
3397 self.MT.del_row_positions(idxs=idxs)
3398 self.set_refresh_timer()
3399 return self
3400
3401 def del_column_position(self, idx: int, deselect_all: bool = False) -> Sheet:
3402 self.MT.del_col_position(idx, deselect_all=deselect_all)
3403 return self
3404
3405 delete_column_position = del_column_position
3406
3407 def del_column_positions(self, idxs: Iterator[int] | None = None) -> Sheet:
3408 self.MT.del_col_positions(idxs=idxs)
3409 self.set_refresh_timer()
3410 return self
3411
3412 def insert_column_position(
3413 self,
3414 idx: Literal["end"] | int = "end",
3415 width: int | None = None,
3416 deselect_all: bool = False,
3417 redraw: bool = False,
3418 ) -> Sheet:
3419 self.MT.insert_col_positions(idx=idx, widths=width, deselect_all=deselect_all)
3420 return self.set_refresh_timer(redraw)
3421
3422 def insert_row_position(
3423 self,
3424 idx: Literal["end"] | int = "end",
3425 height: int | None = None,
3426 deselect_all: bool = False,
3427 redraw: bool = False,
3428 ) -> Sheet:
3429 self.MT.insert_row_positions(idx=idx, heights=height, deselect_all=deselect_all)
3430 return self.set_refresh_timer(redraw)
3431
3432 def insert_column_positions(
3433 self,
3434 idx: Literal["end"] | int = "end",
3435 widths: Sequence[float] | int | None = None,
3436 deselect_all: bool = False,
3437 redraw: bool = False,
3438 ) -> Sheet:
3439 self.MT.insert_col_positions(idx=idx, widths=widths, deselect_all=deselect_all)
3440 return self.set_refresh_timer(redraw)
3441
3442 def insert_row_positions(
3443 self,
3444 idx: Literal["end"] | int = "end",
3445 heights: Sequence[float] | int | None = None,
3446 deselect_all: bool = False,
3447 redraw: bool = False,
3448 ) -> Sheet:
3449 self.MT.insert_row_positions(idx=idx, heights=heights, deselect_all=deselect_all)
3450 return self.set_refresh_timer(redraw)
3451
3452 def sheet_display_dimensions(
3453 self,
3454 total_rows: int | None = None,
3455 total_columns: int | None = None,
3456 ) -> tuple[int, int] | Sheet:
3457 if total_rows is None and total_columns is None:
3458 return len(self.MT.row_positions) - 1, len(self.MT.col_positions) - 1
3459 if isinstance(total_rows, int):
3460 height = self.MT.get_default_row_height()
3461 self.MT.row_positions = list(accumulate(chain([0], repeat(height, total_rows))))
3462 if isinstance(total_columns, int):
3463 width = self.ops.default_column_width
3464 self.MT.col_positions = list(accumulate(chain([0], repeat(width, total_columns))))
3465 return self
3466
3467 def move_row_position(self, row: int, moveto: int) -> Sheet:
3468 self.MT.move_row_position(row, moveto)
3469 return self
3470
3471 def move_column_position(self, column: int, moveto: int) -> Sheet:
3472 self.MT.move_col_position(column, moveto)
3473 return self
3474
3475 def get_example_canvas_column_widths(self, total_cols: int | None = None) -> list[float]:
3476 colpos = int(self.ops.default_column_width)
3477 if isinstance(total_cols, int):
3478 return list(accumulate(chain([0], repeat(colpos, total_cols))))
3479 return list(accumulate(chain([0], repeat(colpos, len(self.MT.col_positions) - 1))))
3480
3481 def get_example_canvas_row_heights(self, total_rows: int | None = None) -> list[float]:
3482 rowpos = self.MT.get_default_row_height()
3483 if isinstance(total_rows, int):
3484 return list(accumulate(chain([0], repeat(rowpos, total_rows))))
3485 return list(accumulate(chain([0], repeat(rowpos, len(self.MT.row_positions) - 1))))
3486
3487 def verify_row_heights(self, row_heights: list[float], canvas_positions: bool = False) -> bool:
3488 if not isinstance(row_heights, list):
3489 return False
3490 if canvas_positions:
3491 if row_heights[0] != 0:
3492 return False
3493 return not any(
3494 x - z < self.MT.min_row_height or not isinstance(x, int) or isinstance(x, bool)
3495 for z, x in zip(row_heights, islice(row_heights, 1, None))
3496 )
3497 return not any(z < self.MT.min_row_height or not isinstance(z, int) or isinstance(z, bool) for z in row_heights)
3498
3499 def verify_column_widths(self, column_widths: list[float], canvas_positions: bool = False) -> bool:
3500 if not isinstance(column_widths, list):
3501 return False
3502 if canvas_positions:
3503 if column_widths[0] != 0:
3504 return False
3505 return not any(
3506 x - z < self.ops.min_column_width or not isinstance(x, int) or isinstance(x, bool)
3507 for z, x in zip(column_widths, islice(column_widths, 1, None))
3508 )
3509 return not any(
3510 z < self.ops.min_column_width or not isinstance(z, int) or isinstance(z, bool) for z in column_widths
3511 )
3512
3513 def valid_row_height(self, height: int) -> int:
3514 if height < self.MT.min_row_height:
3515 return self.MT.min_row_height
3516 elif height > self.ops.max_row_height:
3517 return self.ops.max_row_height
3518 return height
3519
3520 def valid_column_width(self, width: int) -> int:
3521 if width < self.ops.min_column_width:
3522 return self.ops.min_column_width
3523 elif width > self.ops.max_column_width:
3524 return self.ops.max_column_width
3525 return width
3526
3527 @property
3528 def visible_rows(self) -> tuple[int, int]:
3529 """
3530 returns: tuple[visible start row int, visible end row int]
3531 """
3532 return self.MT.visible_text_rows
3533
3534 @property
3535 def visible_columns(self) -> tuple[int, int]:
3536 """
3537 returns: tuple[visible start column int, visible end column int]
3538 """
3539 return self.MT.visible_text_columns
3540
3541 # Identifying Bound Event Mouse Position
3542
3543 def identify_region(self, event: Any) -> Literal["table", "index", "header", "top left"]:
3544 if event.widget == self.MT:
3545 return "table"
3546 elif event.widget == self.RI:
3547 return "index"
3548 elif event.widget == self.CH:
3549 return "header"
3550 elif event.widget == self.TL:
3551 return "top left"
3552
3553 def identify_row(
3554 self,
3555 event: Any,
3556 exclude_index: bool = False,
3557 allow_end: bool = True,
3558 ) -> int | None:
3559 ev_w = event.widget
3560 if ev_w == self.MT:
3561 return self.MT.identify_row(y=event.y, allow_end=allow_end)
3562 elif ev_w == self.RI:
3563 if exclude_index:
3564 return None
3565 else:
3566 return self.MT.identify_row(y=event.y, allow_end=allow_end)
3567 elif ev_w == self.CH or ev_w == self.TL:
3568 return None
3569
3570 def identify_column(
3571 self,
3572 event: Any,
3573 exclude_header: bool = False,
3574 allow_end: bool = True,
3575 ) -> int | None:
3576 ev_w = event.widget
3577 if ev_w == self.MT:
3578 return self.MT.identify_col(x=event.x, allow_end=allow_end)
3579 elif ev_w == self.RI or ev_w == self.TL:
3580 return None
3581 elif ev_w == self.CH:
3582 if exclude_header:
3583 return None
3584 else:
3585 return self.MT.identify_col(x=event.x, allow_end=allow_end)
3586
3587 # Scroll Positions and Cell Visibility
3588
3589 def sync_scroll(self, widget: Any) -> Sheet:
3590 if widget is self:
3591 return self
3592 self.MT.synced_scrolls.add(widget)
3593 if isinstance(widget, Sheet):
3594 widget.MT.synced_scrolls.add(self)
3595 return self
3596
3597 def unsync_scroll(self, widget: Any = None) -> Sheet:
3598 if widget is None:
3599 for widget in self.MT.synced_scrolls:
3600 if isinstance(widget, Sheet):
3601 widget.MT.synced_scrolls.discard(self)
3602 self.MT.synced_scrolls = set()
3603 else:
3604 if isinstance(widget, Sheet) and self in widget.MT.synced_scrolls:
3605 widget.MT.synced_scrolls.discard(self)
3606 self.MT.synced_scrolls.discard(widget)
3607 return self
3608
3609 def see(
3610 self,
3611 row: int = 0,
3612 column: int = 0,
3613 keep_yscroll: bool = False,
3614 keep_xscroll: bool = False,
3615 bottom_right_corner: bool | None = None,
3616 check_cell_visibility: bool = True,
3617 redraw: bool = True,
3618 ) -> Sheet:
3619 self.MT.see(
3620 row,
3621 column,
3622 keep_yscroll,
3623 keep_xscroll,
3624 bottom_right_corner,
3625 check_cell_visibility=check_cell_visibility,
3626 redraw=False,
3627 )
3628 return self.set_refresh_timer(redraw)
3629
3630 def cell_visible(self, r: int, c: int) -> bool:
3631 return self.MT.cell_visible(r, c)
3632
3633 def cell_completely_visible(self, r: int, c: int, seperate_axes: bool = False) -> bool:
3634 if seperate_axes:
3635 d = self.MT.cell_visibility_info(r, c)
3636 return d["yvis"], d["xvis"]
3637 else:
3638 return self.MT.cell_completely_visible(r, c)
3639
3640 def set_xview(self, position: None | float = None, option: str = "moveto") -> Sheet | tuple[float, float]:
3641 if position is not None:
3642 self.MT.set_xviews(option, position)
3643 return self
3644 return self.MT.xview()
3645
3646 xview = set_xview
3647 xview_moveto = set_xview
3648
3649 def set_yview(self, position: None | float = None, option: str = "moveto") -> Sheet | tuple[float, float]:
3650 if position is not None:
3651 self.MT.set_yviews(option, position)
3652 return self
3653 return self.MT.yview()
3654
3655 yview = set_yview
3656 yview_moveto = set_yview
3657
3658 def set_view(self, x_args: list[str, float], y_args: list[str, float]) -> Sheet:
3659 self.MT.set_view(x_args, y_args)
3660 return self
3661
3662 def get_xview(self) -> tuple[float, float]:
3663 return self.MT.xview()
3664
3665 def get_yview(self) -> tuple[float, float]:
3666 return self.MT.yview()
3667
3668 # Hiding Columns
3669
3670 def displayed_column_to_data(self, c: int) -> int:
3671 return c if self.MT.all_columns_displayed else self.MT.displayed_columns[c]
3672
3673 data_c = displayed_column_to_data
3674 datacn = displayed_column_to_data
3675 dcol = displayed_column_to_data
3676
3677 def data_column_to_displayed(self, c: int) -> int:
3678 return self.MT.dispcn(c)
3679
3680 dispcn = data_column_to_displayed
3681
3682 def display_columns(
3683 self,
3684 columns: None | Literal["all"] | Iterator[int] = None,
3685 all_columns_displayed: None | bool = None,
3686 reset_col_positions: bool = True,
3687 redraw: bool = False,
3688 deselect_all: bool = True,
3689 **kwargs,
3690 ) -> list[int] | None:
3691 if "all_displayed" in kwargs:
3692 all_columns_displayed = kwargs["all_displayed"]
3693 res = self.MT.display_columns(
3694 columns=None if isinstance(columns, str) and columns.lower() == "all" else columns,
3695 all_columns_displayed=(
3696 True if isinstance(columns, str) and columns.lower() == "all" else all_columns_displayed
3697 ),
3698 reset_col_positions=reset_col_positions,
3699 deselect_all=deselect_all,
3700 )
3701 if "refresh" in kwargs:
3702 redraw = kwargs["refresh"]
3703 self.set_refresh_timer(redraw)
3704 return res
3705
3706 def hide_columns(
3707 self,
3708 columns: int | set[int] | Iterator[int],
3709 redraw: bool = True,
3710 deselect_all: bool = True,
3711 data_indexes: bool = False,
3712 ) -> Sheet:
3713 if isinstance(columns, int):
3714 columns = {columns}
3715 elif not isinstance(columns, set):
3716 columns = set(columns)
3717 if not columns:
3718 return
3719 if self.MT.all_columns_displayed:
3720 self.MT.displayed_columns = list(filterfalse(columns.__contains__, range(self.MT.total_data_cols())))
3721 to_pop = {c: c for c in columns}
3722 else:
3723 to_pop = {}
3724 new_disp = []
3725 if data_indexes:
3726 for i, c in enumerate(self.MT.displayed_columns):
3727 if c not in columns:
3728 new_disp.append(c)
3729 else:
3730 to_pop[i] = c
3731 else:
3732 for i, c in enumerate(self.MT.displayed_columns):
3733 if i not in columns:
3734 new_disp.append(c)
3735 else:
3736 to_pop[i] = c
3737 self.MT.displayed_columns = new_disp
3738 self.MT.all_columns_displayed = False
3739 self.MT.set_col_positions(
3740 pop_positions(
3741 itr=self.MT.gen_column_widths,
3742 to_pop=to_pop,
3743 save_to=self.MT.saved_column_widths,
3744 ),
3745 )
3746 if deselect_all:
3747 self.MT.deselect(redraw=False)
3748 return self.set_refresh_timer(redraw)
3749
3750 def show_columns(
3751 self,
3752 columns: int | Iterator[int],
3753 redraw: bool = True,
3754 deselect_all: bool = True,
3755 ) -> Sheet:
3756 """
3757 'columns' argument must be data indexes
3758 Function will return without action if Sheet.all_columns
3759 """
3760 if self.MT.all_columns_displayed:
3761 return
3762 if isinstance(columns, int):
3763 columns = [columns]
3764 cws = self.MT.get_column_widths()
3765 default_col_w = self.ops.default_column_width
3766 for column in columns:
3767 idx = bisect_left(self.MT.displayed_columns, column)
3768 if len(self.MT.displayed_columns) == idx or self.MT.displayed_columns[idx] != column:
3769 self.MT.displayed_columns.insert(idx, column)
3770 cws.insert(idx, self.MT.saved_column_widths.pop(column, default_col_w))
3771 self.MT.set_col_positions(cws)
3772 if deselect_all:
3773 self.MT.deselect(redraw=False)
3774 return self.set_refresh_timer(redraw)
3775
3776 def all_columns_displayed(self, a: bool | None = None) -> bool:
3777 v = bool(self.MT.all_columns_displayed)
3778 if isinstance(a, bool):
3779 self.MT.all_columns_displayed = a
3780 return v
3781
3782 @property
3783 def all_columns(self) -> bool:
3784 return self.MT.all_columns_displayed
3785
3786 @all_columns.setter
3787 def all_columns(self, a: bool) -> Sheet:
3788 self.MT.display_columns(
3789 columns=None,
3790 all_columns_displayed=a,
3791 )
3792 return self
3793
3794 @property
3795 def displayed_columns(self) -> list[int]:
3796 return self.MT.displayed_columns
3797
3798 @displayed_columns.setter
3799 def displayed_columns(self, columns: list[int]) -> Sheet:
3800 self.display_columns(columns=columns, reset_col_positions=True, redraw=False)
3801 return self.set_refresh_timer()
3802
3803 # Hiding Rows
3804
3805 def displayed_row_to_data(self, r: int) -> int:
3806 return r if self.MT.all_rows_displayed else self.MT.displayed_rows[r]
3807
3808 data_r = displayed_row_to_data
3809 datarn = displayed_row_to_data
3810 drow = displayed_row_to_data
3811
3812 def data_row_to_displayed(self, r: int) -> int:
3813 return self.MT.disprn(r)
3814
3815 disprn = data_row_to_displayed
3816
3817 def display_rows(
3818 self,
3819 rows: None | Literal["all"] | Iterator[int] = None,
3820 all_rows_displayed: None | bool = None,
3821 reset_row_positions: bool = True,
3822 redraw: bool = False,
3823 deselect_all: bool = True,
3824 **kwargs,
3825 ) -> list[int] | None:
3826 if "all_displayed" in kwargs:
3827 all_rows_displayed = kwargs["all_displayed"]
3828 res = self.MT.display_rows(
3829 rows=None if isinstance(rows, str) and rows.lower() == "all" else rows,
3830 all_rows_displayed=True if isinstance(rows, str) and rows.lower() == "all" else all_rows_displayed,
3831 reset_row_positions=reset_row_positions,
3832 deselect_all=deselect_all,
3833 )
3834 if "refresh" in kwargs:
3835 redraw = kwargs["refresh"]
3836 self.set_refresh_timer(redraw)
3837 return res
3838
3839 def hide_rows(
3840 self,
3841 rows: int | set[int] | Iterator[int],
3842 redraw: bool = True,
3843 deselect_all: bool = True,
3844 data_indexes: bool = False,
3845 row_heights: bool = True,
3846 ) -> Sheet:
3847 if isinstance(rows, int):
3848 rows = {rows}
3849 elif not isinstance(rows, set):
3850 rows = set(rows)
3851 if not rows:
3852 return
3853 if self.MT.all_rows_displayed:
3854 self.MT.displayed_rows = list(filterfalse(rows.__contains__, range(self.MT.total_data_rows())))
3855 to_pop = {r: r for r in rows}
3856 else:
3857 to_pop = {}
3858 new_disp = []
3859 if data_indexes:
3860 for i, r in enumerate(self.MT.displayed_rows):
3861 if r not in rows:
3862 new_disp.append(r)
3863 else:
3864 to_pop[i] = r
3865 else:
3866 for i, r in enumerate(self.MT.displayed_rows):
3867 if i not in rows:
3868 new_disp.append(r)
3869 else:
3870 to_pop[i] = r
3871 self.MT.displayed_rows = new_disp
3872 self.MT.all_rows_displayed = False
3873 if row_heights:
3874 self.MT.set_row_positions(
3875 pop_positions(
3876 itr=self.MT.gen_row_heights,
3877 to_pop=to_pop,
3878 save_to=self.MT.saved_row_heights,
3879 ),
3880 )
3881 if deselect_all:
3882 self.MT.deselect(redraw=False)
3883 return self.set_refresh_timer(redraw)
3884
3885 def show_rows(
3886 self,
3887 rows: int | Iterator[int],
3888 redraw: bool = True,
3889 deselect_all: bool = True,
3890 ) -> Sheet:
3891 """
3892 'rows' argument must be data indexes
3893 Function will return without action if Sheet.all_rows
3894 """
3895 if self.MT.all_rows_displayed:
3896 return
3897 if isinstance(rows, int):
3898 rows = [rows]
3899 default_row_h = self.MT.get_default_row_height()
3900 rhs = self.MT.get_row_heights()
3901 for row in rows:
3902 idx = bisect_left(self.MT.displayed_rows, row)
3903 if len(self.MT.displayed_rows) == idx or self.MT.displayed_rows[idx] != row:
3904 self.MT.displayed_rows.insert(idx, row)
3905 rhs.insert(idx, self.MT.saved_row_heights.pop(row, default_row_h))
3906 self.MT.set_row_positions(rhs)
3907 if deselect_all:
3908 self.MT.deselect(redraw=False)
3909 return self.set_refresh_timer(redraw)
3910
3911 def all_rows_displayed(self, a: bool | None = None) -> bool:
3912 v = bool(self.MT.all_rows_displayed)
3913 if isinstance(a, bool):
3914 self.MT.all_rows_displayed = a
3915 return v
3916
3917 @property
3918 def all_rows(self) -> bool:
3919 return self.MT.all_rows_displayed
3920
3921 @all_rows.setter
3922 def all_rows(self, a: bool) -> Sheet:
3923 self.MT.display_rows(
3924 rows=None,
3925 all_rows_displayed=a,
3926 )
3927 return self
3928
3929 @property
3930 def displayed_rows(self) -> list[int]:
3931 return self.MT.displayed_rows
3932
3933 @displayed_rows.setter
3934 def displayed_rows(self, rows: list[int]) -> Sheet:
3935 self.display_rows(rows=rows, reset_row_positions=True, redraw=False)
3936 return self.set_refresh_timer()
3937
3938 # Hiding Sheet Elements
3939
3940 def show(
3941 self,
3942 canvas: Literal[
3943 "all",
3944 "row_index",
3945 "index",
3946 "header",
3947 "top_left",
3948 "x_scrollbar",
3949 "y_scrollbar",
3950 "table",
3951 ] = "all",
3952 ) -> Sheet:
3953 if canvas in ("all", "table"):
3954 self.MT.grid(row=1, column=1, sticky="nswe")
3955 if canvas in ("all", "row_index", "index"):
3956 self.RI.grid(row=1, column=0, sticky="nswe")
3957 self.MT.show_index = True
3958 if canvas in ("all", "header"):
3959 self.CH.grid(row=0, column=1, sticky="nswe")
3960 self.MT.show_header = True
3961 if canvas in ("all", "top_left") or (
3962 self.ops.show_top_left is not False and self.MT.show_header and self.MT.show_index
3963 ):
3964 self.TL.grid(row=0, column=0)
3965 if canvas in ("all", "x_scrollbar"):
3966 self.xscroll.grid(row=2, column=0, columnspan=2, sticky="nswe")
3967 self.xscroll_showing = True
3968 self.xscroll_disabled = False
3969 if canvas in ("all", "y_scrollbar"):
3970 self.yscroll.grid(row=0, column=2, rowspan=3, sticky="nswe")
3971 self.yscroll_showing = True
3972 self.yscroll_disabled = False
3973 if self._startup_complete:
3974 self.MT.update_idletasks()
3975 return self
3976
3977 def hide(
3978 self,
3979 canvas: Literal[
3980 "all",
3981 "row_index",
3982 "header",
3983 "top_left",
3984 "x_scrollbar",
3985 "y_scrollbar",
3986 "table",
3987 ] = "all",
3988 ) -> Sheet:
3989 if canvas in ("all", "row_index"):
3990 self.RI.grid_remove()
3991 self.MT.show_index = False
3992 if canvas in ("all", "header"):
3993 self.CH.grid_remove()
3994 self.MT.show_header = False
3995 if canvas in ("all", "top_left") or (
3996 not self.ops.show_top_left and (not self.MT.show_index or not self.MT.show_header)
3997 ):
3998 self.TL.grid_remove()
3999 if canvas in ("all", "x_scrollbar"):
4000 self.xscroll.grid_remove()
4001 self.xscroll_showing = False
4002 self.xscroll_disabled = True
4003 if canvas in ("all", "y_scrollbar"):
4004 self.yscroll.grid_remove()
4005 self.yscroll_showing = False
4006 self.yscroll_disabled = True
4007 if canvas in ("all", "table"):
4008 self.MT.grid_remove()
4009 return self
4010
4011 # Sheet Height and Width
4012
4013 def height_and_width(
4014 self,
4015 height: int | None = None,
4016 width: int | None = None,
4017 ) -> Sheet:
4018 if width is not None or height is not None:
4019 self.grid_propagate(0)
4020 elif width is None and height is None:
4021 self.grid_propagate(1)
4022 if width is not None:
4023 self.config(width=width)
4024 if height is not None:
4025 self.config(height=height)
4026 return self
4027
4028 def get_frame_y(self, y: int) -> int:
4029 return y + self.CH.current_height
4030
4031 def get_frame_x(self, x: int) -> int:
4032 return x + self.RI.current_width
4033
4034 # Cell Text Editor
4035
4036 def next_cell(self, r: int, c: int, key: Literal["Return", "Tab", "??"]) -> Sheet:
4037 self.MT.go_to_next_cell(r, c, key)
4038 return self
4039
4040 # works on currently selected box
4041 def open_cell(self, ignore_existing_editor: bool = True) -> Sheet:
4042 self.MT.open_cell(event=GeneratedMouseEvent(), ignore_existing_editor=ignore_existing_editor)
4043 return self
4044
4045 def open_header_cell(self, ignore_existing_editor: bool = True) -> Sheet:
4046 self.CH.open_cell(event=GeneratedMouseEvent(), ignore_existing_editor=ignore_existing_editor)
4047 return self
4048
4049 def open_index_cell(self, ignore_existing_editor: bool = True) -> Sheet:
4050 self.RI.open_cell(event=GeneratedMouseEvent(), ignore_existing_editor=ignore_existing_editor)
4051 return self
4052
4053 def set_text_editor_value(
4054 self,
4055 text: str = "",
4056 ) -> Sheet:
4057 if self.MT.text_editor.open:
4058 self.MT.text_editor.window.set_text(text)
4059 return self
4060
4061 def set_index_text_editor_value(
4062 self,
4063 text: str = "",
4064 ) -> Sheet:
4065 if self.RI.text_editor.open:
4066 self.RI.text_editor.window.set_text(text)
4067 return self
4068
4069 def set_header_text_editor_value(
4070 self,
4071 text: str = "",
4072 ) -> Sheet:
4073 if self.CH.text_editor.open:
4074 self.CH.text_editor.window.set_text(text)
4075 return self
4076
4077 def destroy_text_editor(self, event: Any = None) -> Sheet:
4078 self.MT.hide_text_editor(reason=event)
4079 self.RI.hide_text_editor(reason=event)
4080 self.CH.hide_text_editor(reason=event)
4081 return self
4082
4083 def get_text_editor_widget(self, event: Any = None) -> tk.Text | None:
4084 try:
4085 return self.MT.text_editor.tktext
4086 except Exception:
4087 return None
4088
4089 def bind_key_text_editor(self, key: str, function: Callable) -> Sheet:
4090 self.MT.text_editor_user_bound_keys[key] = function
4091 return self
4092
4093 def unbind_key_text_editor(self, key: str) -> Sheet:
4094 if key == "all":
4095 for key in self.MT.text_editor_user_bound_keys:
4096 with suppress(Exception):
4097 self.MT.text_editor.tktext.unbind(key)
4098 self.MT.text_editor_user_bound_keys = {}
4099 else:
4100 if key in self.MT.text_editor_user_bound_keys:
4101 del self.MT.text_editor_user_bound_keys[key]
4102 with suppress(Exception):
4103 self.MT.text_editor.tktext.unbind(key)
4104 return self
4105
4106 def get_text_editor_value(self) -> str | None:
4107 return self.MT.text_editor.get()
4108
4109 def close_text_editor(self, set_data: bool = True) -> Sheet:
4110 event = new_tk_event("ButtonPress-1" if set_data else "Escape")
4111 if self.MT.text_editor.open:
4112 self.MT.close_text_editor(event=event)
4113 if self.RI.text_editor.open:
4114 self.RI.close_text_editor(event=event)
4115 if self.CH.text_editor.open:
4116 self.CH.close_text_editor(event=event)
4117 return self
4118
4119 # Sheet Options and Other Functions
4120
4121 def set_options(self, redraw: bool = True, **kwargs) -> Sheet:
4122 enabled = tuple(self.MT.enabled_bindings)
4123 for k, v in kwargs.items():
4124 if k in self.ops and v != self.ops[k]:
4125 if k.endswith("bindings"):
4126 for b in enabled:
4127 self.MT._disable_binding(b)
4128 self.ops[k] = v
4129 if k.endswith("bindings"):
4130 for b in enabled:
4131 self.MT._enable_binding(b)
4132 if "name" in kwargs:
4133 self.name = kwargs["name"]
4134 if "min_column_width" in kwargs:
4135 self.MT.set_min_column_width(kwargs["min_column_width"])
4136 if "from_clipboard_delimiters" in kwargs:
4137 self.ops.from_clipboard_delimiters = (
4138 self.ops.from_clipboard_delimiters
4139 if isinstance(self.ops.from_clipboard_delimiters, str)
4140 else "".join(self.ops.from_clipboard_delimiters)
4141 )
4142 if "default_row_height" in kwargs:
4143 self.default_row_height(kwargs["default_row_height"])
4144 if "expand_sheet_if_paste_too_big" in kwargs:
4145 self.ops.paste_can_expand_x = kwargs["expand_sheet_if_paste_too_big"]
4146 self.ops.paste_can_expand_y = kwargs["expand_sheet_if_paste_too_big"]
4147 if "show_top_left" in kwargs:
4148 self.show("top_left")
4149 if "font" in kwargs:
4150 self.MT.set_table_font(kwargs["font"])
4151 elif "table_font" in kwargs:
4152 self.MT.set_table_font(kwargs["table_font"])
4153 if "header_font" in kwargs:
4154 self.MT.set_header_font(kwargs["header_font"])
4155 if "index_font" in kwargs:
4156 self.MT.set_index_font(kwargs["index_font"])
4157 if "theme" in kwargs:
4158 self.change_theme(kwargs["theme"])
4159 if "header_bg" in kwargs:
4160 self.CH.config(background=kwargs["header_bg"])
4161 if "index_bg" in kwargs:
4162 self.RI.config(background=kwargs["index_bg"])
4163 if "top_left_bg" in kwargs:
4164 self.TL.config(background=kwargs["top_left_bg"])
4165 self.TL.itemconfig(self.TL.select_all_box, fill=kwargs["top_left_bg"])
4166 if "top_left_fg" in kwargs:
4167 self.TL.itemconfig("rw", fill=kwargs["top_left_fg"])
4168 self.TL.itemconfig("rh", fill=kwargs["top_left_fg"])
4169 if "frame_bg" in kwargs:
4170 self.config(background=kwargs["frame_bg"])
4171 if "table_bg" in kwargs:
4172 self.MT.config(background=kwargs["table_bg"])
4173 if "outline_thickness" in kwargs:
4174 self.config(highlightthickness=kwargs["outline_thickness"])
4175 if "outline_color" in kwargs:
4176 self.config(
4177 highlightbackground=kwargs["outline_color"],
4178 highlightcolor=kwargs["outline_color"],
4179 )
4180 if any(k in kwargs for k in scrollbar_options_keys):
4181 self.set_scrollbar_options()
4182 self.MT.create_rc_menus()
4183 if "treeview" in kwargs:
4184 self.index_align("nw", redraw=False)
4185 return self.set_refresh_timer(redraw)
4186
4187 def set_scrollbar_options(self) -> Sheet:
4188 style = ttk.Style()
4189 for orientation in ("vertical", "horizontal"):
4190 style.configure(
4191 f"Sheet{self.unique_id}.{orientation.capitalize()}.TScrollbar",
4192 background=self.ops[f"{orientation}_scroll_background"],
4193 troughcolor=self.ops[f"{orientation}_scroll_troughcolor"],
4194 lightcolor=self.ops[f"{orientation}_scroll_lightcolor"],
4195 darkcolor=self.ops[f"{orientation}_scroll_darkcolor"],
4196 relief=self.ops[f"{orientation}_scroll_relief"],
4197 troughrelief=self.ops[f"{orientation}_scroll_troughrelief"],
4198 bordercolor=self.ops[f"{orientation}_scroll_bordercolor"],
4199 borderwidth=self.ops[f"{orientation}_scroll_borderwidth"],
4200 gripcount=self.ops[f"{orientation}_scroll_gripcount"],
4201 arrowsize=self.ops[f"{orientation}_scroll_arrowsize"],
4202 )
4203 style.map(
4204 f"Sheet{self.unique_id}.{orientation.capitalize()}.TScrollbar",
4205 foreground=[
4206 ("!active", self.ops[f"{orientation}_scroll_not_active_fg"]),
4207 ("pressed", self.ops[f"{orientation}_scroll_pressed_fg"]),
4208 ("active", self.ops[f"{orientation}_scroll_active_fg"]),
4209 ],
4210 background=[
4211 ("!active", self.ops[f"{orientation}_scroll_not_active_bg"]),
4212 ("pressed", self.ops[f"{orientation}_scroll_pressed_bg"]),
4213 ("active", self.ops[f"{orientation}_scroll_active_bg"]),
4214 ],
4215 )
4216 return self
4217
4218 def event_widget_is_sheet(
4219 self,
4220 event: Any,
4221 table: bool = True,
4222 index: bool = True,
4223 header: bool = True,
4224 top_left: bool = True,
4225 ) -> bool:
4226 return (
4227 table
4228 and event.widget == self.MT
4229 or index
4230 and event.widget == self.RI
4231 or header
4232 and event.widget == self.CH
4233 or top_left
4234 and event.widget == self.TL
4235 )
4236
4237 def props(
4238 self,
4239 row: int,
4240 column: int | str,
4241 key: None | CellPropertyKey = None,
4242 cellops: bool = True,
4243 rowops: bool = True,
4244 columnops: bool = True,
4245 ) -> dict:
4246 """
4247 Retrieve options (properties - props)
4248 from a single cell in the main table
4249
4250 Also retrieves any row or column options
4251 impacting that cell
4252 """
4253 return self.MT.get_cell_kwargs(
4254 datarn=row,
4255 datacn=alpha2idx(column) if isinstance(column, str) else column,
4256 key=key,
4257 cell=cellops,
4258 row=rowops,
4259 column=columnops,
4260 )
4261
4262 def index_props(
4263 self,
4264 row: int,
4265 key: None | CellPropertyKey = None,
4266 ) -> dict:
4267 """
4268 Retrieve options (properties - props)
4269 from a cell in the index
4270 """
4271 return self.RI.get_cell_kwargs(
4272 datarn=row,
4273 key=key,
4274 )
4275
4276 def header_props(
4277 self,
4278 column: int | str,
4279 key: None | CellPropertyKey = None,
4280 ) -> dict:
4281 """
4282 Retrieve options (properties - props)
4283 from a cell in the header
4284 """
4285 return self.CH.get_cell_kwargs(
4286 datacn=alpha2idx(column) if isinstance(column, str) else column,
4287 key=key,
4288 )
4289
4290 def get_cell_options(
4291 self,
4292 key: None | CellPropertyKey = None,
4293 canvas: Literal["table", "row_index", "index", "header"] = "table",
4294 ) -> dict:
4295 if canvas == "table":
4296 target = self.MT.cell_options
4297 elif canvas in ("row_index", "index"):
4298 target = self.RI.cell_options
4299 elif canvas == "header":
4300 target = self.CH.cell_options
4301 if key is None:
4302 return target
4303 return {k: v[key] for k, v in target.items() if key in v}
4304
4305 def get_row_options(self, key: None | CellPropertyKey = None) -> dict:
4306 if key is None:
4307 return self.MT.row_options
4308 return {k: v[key] for k, v in self.MT.row_options.items() if key in v}
4309
4310 def get_column_options(self, key: None | CellPropertyKey = None) -> dict:
4311 if key is None:
4312 return self.MT.col_options
4313 return {k: v[key] for k, v in self.MT.col_options.items() if key in v}
4314
4315 def get_index_options(self, key: None | CellPropertyKey = None) -> dict:
4316 if key is None:
4317 return self.RI.cell_options
4318 return {k: v[key] for k, v in self.RI.cell_options.items() if key in v}
4319
4320 def get_header_options(self, key: None | CellPropertyKey = None) -> dict:
4321 if key is None:
4322 return self.CH.cell_options
4323 return {k: v[key] for k, v in self.CH.cell_options.items() if key in v}
4324
4325 def del_out_of_bounds_options(self) -> Sheet:
4326 maxc = self.total_columns()
4327 maxr = self.total_rows()
4328 for name in tuple(self.MT.named_spans):
4329 span = self.MT.named_spans[name]
4330 if (
4331 (isinstance(span.upto_r, int) and span.upto_r > maxr)
4332 or (isinstance(span.upto_c, int) and span.upto_c > maxc)
4333 or span.from_r >= maxr
4334 or span.from_c >= maxc
4335 ):
4336 self.del_named_span(name)
4337 self.MT.cell_options = {k: v for k, v in self.MT.cell_options.items() if k[0] < maxr and k[1] < maxc}
4338 self.RI.cell_options = {k: v for k, v in self.RI.cell_options.items() if k < maxr}
4339 self.CH.cell_options = {k: v for k, v in self.CH.cell_options.items() if k < maxc}
4340 self.MT.col_options = {k: v for k, v in self.MT.col_options.items() if k < maxc}
4341 self.MT.row_options = {k: v for k, v in self.MT.row_options.items() if k < maxr}
4342 return self
4343
4344 delete_out_of_bounds_options = del_out_of_bounds_options
4345
4346 def reset_all_options(self) -> Sheet:
4347 self.MT.named_spans = {}
4348 self.MT.cell_options = {}
4349 self.RI.cell_options = {}
4350 self.CH.cell_options = {}
4351 self.MT.col_options = {}
4352 self.MT.row_options = {}
4353 return self
4354
4355 def show_ctrl_outline(
4356 self,
4357 canvas: Literal["table"] = "table",
4358 start_cell: tuple[int, int] = (0, 0),
4359 end_cell: tuple[int, int] = (1, 1),
4360 ) -> Sheet:
4361 self.MT.show_ctrl_outline(canvas=canvas, start_cell=start_cell, end_cell=end_cell)
4362 return self
4363
4364 def reset_undos(self) -> Sheet:
4365 self.MT.purge_undo_and_redo_stack()
4366 return self
4367
4368 def get_undo_stack(self) -> deque:
4369 return self.MT.undo_stack
4370
4371 def get_redo_stack(self) -> deque:
4372 return self.MT.redo_stack
4373
4374 def set_undo_stack(self, stack: deque) -> Sheet:
4375 self.MT.undo_stack = stack
4376 return self
4377
4378 def set_redo_stack(self, stack: deque) -> Sheet:
4379 self.MT.redo_stack = stack
4380 return self
4381
4382 def redraw(self, redraw_header: bool = True, redraw_row_index: bool = True) -> Sheet:
4383 self.MT.main_table_redraw_grid_and_text(redraw_header=redraw_header, redraw_row_index=redraw_row_index)
4384 return self
4385
4386 refresh = redraw
4387
4388 # Progress Bars
4389
4390 def create_progress_bar(
4391 self,
4392 row: int,
4393 column: int,
4394 bg: str,
4395 fg: str,
4396 name: Hashable,
4397 percent: int = 0,
4398 del_when_done: bool = False,
4399 ) -> Sheet:
4400 self.MT.progress_bars[(row, column)] = ProgressBar(
4401 bg=bg,
4402 fg=fg,
4403 name=name,
4404 percent=percent,
4405 del_when_done=del_when_done,
4406 )
4407 return self.set_refresh_timer()
4408
4409 def progress_bar(
4410 self,
4411 name: Hashable | None = None,
4412 cell: tuple[int, int] | None = None,
4413 percent: int | None = None,
4414 bg: str | None = None,
4415 fg: str | None = None,
4416 ) -> Sheet:
4417 if name is not None:
4418 bars = (bar for bar in self.MT.progress_bars.values() if bar.name == name)
4419 elif cell is not None:
4420 bars = (self.MT.progress_bars[cell],)
4421 for bar in bars:
4422 if isinstance(percent, int):
4423 bar.percent = percent
4424 if isinstance(bg, str):
4425 bar.bg = bg
4426 if isinstance(fg, str):
4427 bar.fg = fg
4428 return self.set_refresh_timer()
4429
4430 def del_progress_bar(
4431 self,
4432 name: Hashable | None = None,
4433 cell: tuple[int, int] | None = None,
4434 ) -> Sheet:
4435 if name is not None:
4436 for cell in tuple(cell for cell, bar in self.MT.progress_bars.items() if bar.name == name):
4437 del self.MT.progress_bars[cell]
4438 elif cell is not None:
4439 del self.MT.progress_bars[cell]
4440 return self.set_refresh_timer()
4441
4442 # Tags
4443
4444 def tag(
4445 self,
4446 *key: CreateSpanTypes,
4447 tags: Iterator[str] | str = "",
4448 ) -> Sheet:
4449 span = self.span_from_key(*key)
4450 rows, cols = self.ranges_from_span(span)
4451 if isinstance(tags, str):
4452 tags = (tags,)
4453 if span.kind == "cell":
4454 for tag in tags:
4455 if tag not in self.MT.tagged_cells:
4456 self.MT.tagged_cells[tag] = set()
4457 for r in rows:
4458 for c in cols:
4459 self.MT.tagged_cells[tag].add((r, c))
4460 elif span.kind == "row":
4461 for tag in tags:
4462 if tag not in self.MT.tagged_rows:
4463 self.MT.tagged_rows[tag] = set()
4464 self.MT.tagged_rows[tag].update(set(rows))
4465 elif span.kind == "column":
4466 for tag in tags:
4467 if tag not in self.MT.tagged_columns:
4468 self.MT.tagged_columns[tag] = set()
4469 self.MT.tagged_columns[tag].update(set(cols))
4470 return self
4471
4472 def tag_cell(
4473 self,
4474 cell: tuple[int, int],
4475 *tags,
4476 ) -> Sheet:
4477 if (
4478 not isinstance(cell, tuple)
4479 or not len(cell) == 2
4480 or not isinstance(cell[0], int)
4481 or not isinstance(cell[1], int)
4482 ):
4483 raise ValueError("'cell' argument must be tuple[int, int].")
4484 for tag in unpack(tags):
4485 if tag not in self.MT.tagged_cells:
4486 self.MT.tagged_cells[tag] = set()
4487 self.MT.tagged_cells[tag].add(cell)
4488 return self
4489
4490 def tag_rows(
4491 self,
4492 rows: int | Iterator[int],
4493 *tags,
4494 ) -> Sheet:
4495 if isinstance(rows, int):
4496 rows = [rows]
4497 for tag in unpack(tags):
4498 if tag not in self.MT.tagged_rows:
4499 self.MT.tagged_rows[tag] = set()
4500 self.MT.tagged_rows[tag].update(rows)
4501 return self
4502
4503 def tag_columns(
4504 self,
4505 columns: int | Iterator[int],
4506 *tags,
4507 ) -> Sheet:
4508 if isinstance(columns, int):
4509 columns = [columns]
4510 for tag in unpack(tags):
4511 if tag not in self.MT.tagged_columns:
4512 self.MT.tagged_columns[tag] = set()
4513 self.MT.tagged_columns[tag].update(columns)
4514 return self
4515
4516 def untag(
4517 self,
4518 cell: tuple[int, int] | None = None,
4519 rows: int | Iterator[int] | None = None,
4520 columns: int | Iterator[int] | None = None,
4521 ) -> Sheet:
4522 if isinstance(cell, tuple):
4523 for tagged in self.MT.tagged_cells.values():
4524 tagged.discard(cell)
4525 if isinstance(rows, int):
4526 rows = (rows,)
4527 if is_iterable(rows):
4528 for tagged in self.MT.tagged_rows.values():
4529 for row in rows:
4530 tagged.discard(row)
4531 if isinstance(columns, int):
4532 columns = (columns,)
4533 if is_iterable(columns):
4534 for tagged in self.MT.tagged_columns.values():
4535 for column in columns:
4536 tagged.discard(column)
4537 return self
4538
4539 def tag_del(
4540 self,
4541 *tags,
4542 cells: bool = True,
4543 rows: bool = True,
4544 columns: bool = True,
4545 ) -> Sheet:
4546 for tag in unpack(tags):
4547 if cells and tag in self.MT.tagged_cells:
4548 del self.MT.tagged_cells[tag]
4549 if rows and tag in self.MT.tagged_rows:
4550 del self.MT.tagged_rows[tag]
4551 if columns and tag in self.MT.tagged_columns:
4552 del self.MT.tagged_columns[tag]
4553 return self
4554
4555 def tag_has(
4556 self,
4557 *tags,
4558 ) -> DotDict:
4559 res = DotDict(
4560 cells=set(),
4561 rows=set(),
4562 columns=set(),
4563 )
4564 for tag in unpack(tags):
4565 res.cells.update(self.MT.tagged_cells.get(tag, set()))
4566 res.rows.update(self.MT.tagged_rows.get(tag, set()))
4567 res.columns.update(self.MT.tagged_columns.get(tag, set()))
4568 return res
4569
4570 # Treeview Mode
4571
4572 def tree_build(
4573 self,
4574 data: list[list[Any]],
4575 iid_column: int,
4576 parent_column: int,
4577 text_column: None | int | list[str] = None,
4578 push_ops: bool = False,
4579 row_heights: Sequence[int] | None | False = None,
4580 open_ids: Iterator[str] | None = None,
4581 safety: bool = True,
4582 ncols: int | None = None,
4583 lower: bool = False,
4584 include_iid_column: bool = True,
4585 include_parent_column: bool = True,
4586 include_text_column: bool = True,
4587 ) -> Sheet:
4588 build = self.RI.safe_tree_build if safety else self.RI.tree_build
4589 self.reset(cell_options=False, column_widths=False, header=False, redraw=False)
4590 build(
4591 data=data,
4592 iid_column=iid_column,
4593 parent_column=parent_column,
4594 text_column=text_column,
4595 push_ops=push_ops,
4596 row_heights=row_heights,
4597 open_ids=open_ids,
4598 ncols=ncols,
4599 lower=lower,
4600 include_iid_column=include_iid_column,
4601 include_parent_column=include_parent_column,
4602 include_text_column=include_text_column,
4603 )
4604 return self
4605
4606 def tree_reset(self) -> Sheet:
4607 self.deselect()
4608 self.RI.tree_reset()
4609 return self
4610
4611 def tree_get_open(self) -> set[str]:
4612 """
4613 Returns the set[str] of iids that are open in the treeview
4614 """
4615 return self.RI.tree_open_ids
4616
4617 def tree_set_open(self, open_ids: Iterator[str]) -> Sheet:
4618 """
4619 Accepts set[str] of iids that are open in the treeview
4620 Closes everything else
4621 """
4622 self.hide_rows(
4623 rows={rn for rn in self.MT.displayed_rows if self.MT._row_index[rn].parent},
4624 redraw=False,
4625 deselect_all=False,
4626 data_indexes=True,
4627 )
4628 open_ids = set(filter(self.exists, open_ids))
4629 self.RI.tree_open_ids = set()
4630 if open_ids:
4631 self.show_rows(
4632 rows=self._tree_open(open_ids),
4633 redraw=False,
4634 deselect_all=False,
4635 )
4636 return self.set_refresh_timer()
4637
4638 def _tree_open(self, items: set[str]) -> list[int]:
4639 """
4640 Only meant for internal use
4641 """
4642 to_open = []
4643 disp_set = set(self.MT.displayed_rows)
4644 index = self.MT._row_index
4645 rns = self.RI.rns
4646 open_ids = self.RI.tree_open_ids
4647 descendants = self.RI.get_iid_descendants
4648 for item in filter(items.__contains__, self.get_children()):
4649 if index[rns[item]].children:
4650 open_ids.add(item)
4651 if rns[item] in disp_set:
4652 for did in descendants(item, check_open=True):
4653 disp_set.add(rns[did])
4654 to_open.append(rns[did])
4655 return to_open
4656
4657 def tree_open(self, *items, redraw: bool = True) -> Sheet:
4658 """
4659 If used without args all items are opened
4660 """
4661 to_open = self._tree_open(items) if (items := set(unpack(items))) else self._tree_open(set(self.get_children()))
4662 return self.show_rows(
4663 rows=to_open,
4664 redraw=redraw,
4665 deselect_all=False,
4666 )
4667
4668 def _tree_close(self, items: Iterator[str]) -> list[int]:
4669 """
4670 Only meant for internal use
4671 """
4672 to_close = set()
4673 disp_set = set(self.MT.displayed_rows)
4674 index = self.MT._row_index
4675 rns = self.RI.rns
4676 open_ids = self.RI.tree_open_ids
4677 descendants = self.RI.get_iid_descendants
4678 for item in items:
4679 if index[rns[item]].children:
4680 open_ids.discard(item)
4681 if rns[item] in disp_set:
4682 for did in descendants(item, check_open=True):
4683 to_close.add(rns[did])
4684 return to_close
4685
4686 def tree_close(self, *items, redraw: bool = True) -> Sheet:
4687 """
4688 If used without args all items are closed
4689 """
4690 to_close = self._tree_close(unpack(items)) if items else self._tree_close(self.get_children())
4691 return self.hide_rows(
4692 rows=to_close,
4693 redraw=redraw,
4694 deselect_all=False,
4695 data_indexes=True,
4696 )
4697
4698 def insert(
4699 self,
4700 parent: str = "",
4701 index: None | int | Literal["end"] = None,
4702 iid: None | str = None,
4703 text: None | str = None,
4704 values: None | list[Any] = None,
4705 create_selections: bool = False,
4706 undo: bool = True,
4707 ) -> str:
4708 """
4709 Insert an item into the treeview
4710
4711 Returns:
4712 str: new item iid
4713 """
4714 if not iid:
4715 iid = self.RI.new_iid()
4716 if iid in self.RI.rns:
4717 raise ValueError(f"iid '{iid}' already exists.")
4718 if iid == parent:
4719 raise ValueError(f"iid '{iid}' cannot be equal to parent '{parent}'.")
4720 if parent and parent not in self.RI.rns:
4721 raise ValueError(f"parent '{parent}' does not exist.")
4722 if text is None:
4723 text = iid
4724 new_node = Node(text, iid, parent)
4725 datarn = self._get_id_insert_row(index=index, parent=parent)
4726 self.insert_rows(
4727 rows=[[new_node] + ([] if values is None else values)],
4728 idx=datarn,
4729 heights=[],
4730 row_index=True,
4731 create_selections=create_selections,
4732 fill=False,
4733 undo=undo,
4734 tree=True,
4735 )
4736 # only relevant here because in rc add rows they are visible and undo sets old open_ids
4737 if parent and (parent not in self.RI.tree_open_ids or not self.item_displayed(parent)):
4738 self.hide_rows(datarn, deselect_all=False, data_indexes=True)
4739 return iid
4740
4741 def _get_id_insert_row(self, index: int, parent: str) -> int:
4742 if parent:
4743 if isinstance(index, int):
4744 index = min(index, len(self.RI.iid_children(parent)))
4745 datarn = (
4746 self.RI.rns[parent]
4747 + index
4748 + 1
4749 + sum(self.RI.num_descendants(cid) for cid in islice(self.get_children(parent), index))
4750 )
4751 else:
4752 datarn = self.RI.rns[parent] + self.RI.num_descendants(parent) + 1
4753 else:
4754 if isinstance(index, int):
4755 datarn = index
4756 if index and (datarn := self.top_index_row(datarn)) is None:
4757 datarn = len(self.MT._row_index)
4758 else:
4759 datarn = len(self.MT._row_index)
4760 return datarn
4761
4762 def bulk_insert(
4763 self,
4764 data: list[list[Any]],
4765 parent: str = "",
4766 index: None | int | Literal["end"] = None,
4767 iid_column: int | None = None,
4768 text_column: int | None | str = None,
4769 create_selections: bool = False,
4770 include_iid_column: bool = True,
4771 include_text_column: bool = True,
4772 undo: bool = True,
4773 ) -> dict[str, int]:
4774 """
4775 Insert multiple items into the treeview at once, under the same parent.
4776
4777 Returns:
4778 dict:
4779 - Keys (str): iid
4780 - Values (int): row numbers
4781 """
4782 to_insert = []
4783 if parent and parent not in self.RI.rns:
4784 raise ValueError(f"parent '{parent}' does not exist.")
4785 datarn = self._get_id_insert_row(index=index, parent=parent)
4786 rns_to_add = {}
4787 for rn, r in enumerate(data, start=datarn):
4788 iid = self.RI.new_iid() if iid_column is None else r[iid_column]
4789 new_node = Node(
4790 r[text_column] if isinstance(text_column, int) else text_column if isinstance(text_column, str) else "",
4791 iid,
4792 parent,
4793 )
4794 exclude = set()
4795 if isinstance(iid_column, int) and not include_iid_column:
4796 exclude.add(iid_column)
4797 if isinstance(text_column, int) and not include_text_column:
4798 exclude.add(text_column)
4799 if exclude:
4800 to_insert.append([new_node] + [e for c, e in enumerate(r) if c not in exclude])
4801 else:
4802 to_insert.append([new_node] + r)
4803 rns_to_add[iid] = rn
4804 self.insert_rows(
4805 rows=to_insert,
4806 idx=datarn,
4807 heights=[],
4808 row_index=True,
4809 create_selections=create_selections,
4810 fill=False,
4811 undo=undo,
4812 tree=True,
4813 )
4814 if parent and (parent not in self.RI.tree_open_ids or not self.item_displayed(parent)):
4815 self.hide_rows(range(datarn, datarn + len(to_insert)), deselect_all=False, data_indexes=True)
4816 return rns_to_add
4817
4818 def item(
4819 self,
4820 item: str,
4821 iid: str | None = None,
4822 text: str | None = None,
4823 values: list | None = None,
4824 open_: bool | None = None,
4825 undo: bool = True,
4826 emit_event: bool = True,
4827 redraw: bool = True,
4828 ) -> DotDict | Sheet:
4829 """
4830 Modify options for item
4831 If no options are set then returns DotDict of options for item
4832 Else returns Sheet
4833 """
4834 if item not in self.RI.rns:
4835 raise ValueError(f"Item '{item}' does not exist.")
4836 get_only = all(param is None for param in (iid, text, values, open_))
4837
4838 if isinstance(open_, bool):
4839 if self.RI.iid_children(item):
4840 if open_:
4841 self.RI.tree_open_ids.add(item)
4842 if self.item_displayed(item):
4843 self.show_rows(
4844 rows=map(self.RI.rns.__getitem__, self.RI.get_iid_descendants(item, check_open=True)),
4845 redraw=False,
4846 deselect_all=False,
4847 )
4848 else:
4849 self.RI.tree_open_ids.discard(item)
4850 if self.item_displayed(item):
4851 self.hide_rows(
4852 rows=set(map(self.RI.rns.__getitem__, self.RI.get_iid_descendants(item, check_open=True))),
4853 redraw=False,
4854 deselect_all=False,
4855 data_indexes=True,
4856 )
4857 else:
4858 self.RI.tree_open_ids.discard(item)
4859
4860 event_data = None if get_only else self.MT.new_event_dict("edit_table", state=True)
4861
4862 if isinstance(text, str):
4863 event_data.cells.index = {self.RI.rns[item]: self.MT._row_index[self.RI.rns[item]].text}
4864 self.MT._row_index[self.RI.rns[item]].text = text
4865
4866 if isinstance(values, list):
4867 span = self.span(self.RI.rns[item], undo=False, emit_event=False)
4868 event_data = self.set_data(span, data=values, event_data=event_data)
4869
4870 if isinstance(iid, str):
4871 if iid in self.RI.rns:
4872 raise ValueError(f"Cannot rename '{iid}', it already exists.")
4873 event_data = self.RI.rename_iid(old=item, new=iid, event_data=event_data)
4874
4875 if event_data:
4876 if undo and self.MT.undo_enabled:
4877 self.MT.undo_stack.append(stored_event_dict(event_data))
4878 if emit_event:
4879 self.emit_event("<<SheetModified>>", event_data)
4880
4881 self.set_refresh_timer(redraw=not get_only and redraw)
4882 if get_only:
4883 return DotDict(
4884 text=self.MT._row_index[self.RI.rns[item]].text,
4885 values=self[self.RI.rns[item]].options(ndim=1).data,
4886 open_=item in self.RI.tree_open_ids,
4887 )
4888 return self
4889
4890 def itemrow(self, item: str) -> int:
4891 try:
4892 return self.RI.rns[item]
4893 except ValueError as error:
4894 raise ValueError(f"item '{item}' does not exist.") from error
4895
4896 def rowitem(self, row: int, data_index: bool = False) -> str | None:
4897 try:
4898 if data_index:
4899 return self.MT._row_index[row].iid
4900 return self.MT._row_index[self.MT.displayed_rows[row]].iid
4901 except Exception:
4902 return None
4903
4904 def get_children(self, item: None | str = None) -> Generator[str]:
4905 if item is None:
4906 yield from map(attrgetter("iid"), self.MT._row_index)
4907 elif item == "":
4908 yield from map(attrgetter("iid"), self.RI.gen_top_nodes())
4909 else:
4910 yield from self.RI.iid_children(item)
4911
4912 def tree_traverse(self, item: None | str = None) -> Generator[str]:
4913 if item is None:
4914 for tiid in map(attrgetter("iid"), self.RI.gen_top_nodes()):
4915 yield tiid
4916 yield from self.RI.get_iid_descendants(tiid)
4917 elif item == "":
4918 yield from map(attrgetter("iid"), self.RI.gen_top_nodes())
4919 else:
4920 yield from self.RI.iid_children(item)
4921
4922 get_iids = tree_traverse
4923
4924 def del_items(self, *items, undo: bool = True) -> Sheet:
4925 """
4926 Also deletes all descendants of items
4927 """
4928 rows = list(map(self.RI.rns.__getitem__, filter(self.exists, unpack(items))))
4929 if rows:
4930 self.del_rows(rows, data_indexes=True, undo=undo)
4931 return self.set_refresh_timer(rows)
4932
4933 def set_children(self, parent: str, *newchildren) -> Sheet:
4934 """
4935 Moves everything in '*newchildren' under 'parent'
4936 """
4937 for iid in unpack(newchildren):
4938 self.move(iid, parent)
4939 return self
4940
4941 def top_index_row(self, index: int) -> int:
4942 try:
4943 return next(self.RI.rns[n.iid] for i, n in enumerate(self.RI.gen_top_nodes()) if i == index)
4944 except Exception:
4945 return None
4946
4947 def move(
4948 self,
4949 item: str,
4950 parent: str,
4951 index: int | None = None,
4952 select: bool = True,
4953 undo: bool = True,
4954 emit_event: bool = False,
4955 ) -> tuple[dict[int, int], dict[int, int], EventDataDict]:
4956 """
4957 Moves item to be under parent as child at index
4958 'parent' can be an empty str which will put the item at top level
4959 """
4960 if item not in self.RI.rns:
4961 raise ValueError(f"Item '{item}' does not exist.")
4962 if parent and parent not in self.RI.rns:
4963 raise ValueError(f"Parent '{parent}' does not exist.")
4964 if self.RI.move_pid_causes_recursive_loop(item, parent):
4965 raise ValueError(f"Item '{item}' causes recursive loop with parent '{parent}.")
4966 data_new_idxs, disp_new_idxs, event_data = self.MT.move_rows_adjust_options_dict(
4967 data_new_idxs={},
4968 data_old_idxs={},
4969 totalrows=None,
4970 disp_new_idxs={},
4971 move_data=True,
4972 move_heights=True,
4973 create_selections=select,
4974 event_data=None,
4975 node_change=(item, parent, index),
4976 )
4977 if undo:
4978 self.MT.undo_stack.append(stored_event_dict(event_data))
4979 if emit_event:
4980 self.emit_event("<<SheetModified>>", event_data)
4981 self.set_refresh_timer()
4982 return data_new_idxs, disp_new_idxs, event_data
4983
4984 reattach = move
4985
4986 def exists(self, item: str) -> bool:
4987 return item in self.RI.rns
4988
4989 def parent(self, item: str) -> str:
4990 if item not in self.RI.rns:
4991 raise ValueError(f"Item '{item}' does not exist.")
4992 return self.RI.iid_parent(item)
4993
4994 def index(self, item: str) -> int:
4995 if item not in self.RI.rns:
4996 raise ValueError(f"Item '{item}' does not exist.")
4997 elif self.RI.iid_parent(item):
4998 return self.RI.parent_node(item).children.index(item)
4999 else:
5000 return next(index for index, iid in enumerate(self.get_children("")) if iid == item)
5001
5002 def item_displayed(self, item: str) -> bool:
5003 """
5004 Check if an item (row) is currently displayed on the sheet
5005 - Does not check if the item is visible to the user
5006 """
5007 if item not in self.RI.rns:
5008 raise ValueError(f"Item '{item}' does not exist.")
5009 return bisect_in(self.MT.displayed_rows, self.RI.rns[item])
5010
5011 def display_item(self, item: str, redraw: bool = False) -> Sheet:
5012 """
5013 Ensure that item is displayed in the tree
5014 - Opens all of an item's ancestors
5015 - Unlike the ttk treeview 'see' function
5016 this function does **NOT** scroll to the item
5017 """
5018 if not self.item_displayed(item) and self.RI.iid_parent(item):
5019 self.show_rows(
5020 rows=self._tree_open(list(self.RI.get_iid_ancestors(item))),
5021 redraw=False,
5022 deselect_all=False,
5023 )
5024 return self.set_refresh_timer(redraw)
5025
5026 def scroll_to_item(self, item: str, redraw: bool = False) -> Sheet:
5027 """
5028 Scrolls to an item and ensures that it is displayed
5029 """
5030 self.display_item(item, redraw=False)
5031 self.see(
5032 row=bisect_left(self.MT.displayed_rows, self.RI.rns[item]),
5033 keep_xscroll=True,
5034 redraw=False,
5035 )
5036 return self.set_refresh_timer(redraw)
5037
5038 def selection(self, cells: bool = False) -> list[str]:
5039 """
5040 Get currently selected item ids
5041 """
5042 return [
5043 self.MT._row_index[self.MT.displayed_rows[rn]].iid for rn in self.get_selected_rows(get_cells_as_rows=cells)
5044 ]
5045
5046 @property
5047 def tree_selected(self) -> str | None:
5048 """
5049 Get the iid at the currently selected box
5050 """
5051 if selected := self.selected:
5052 return self.rowitem(selected.row)
5053 return None
5054
5055 def selection_set(self, *items, run_binding: bool = True, redraw: bool = True) -> Sheet:
5056 boxes_to_hide = tuple(self.MT.selection_boxes)
5057 self.selection_add(*items, run_binding=False, redraw=False)
5058 for iid in boxes_to_hide:
5059 self.MT.hide_selection_box(iid)
5060 if run_binding:
5061 self.MT.run_selection_binding("rows")
5062 return self.set_refresh_timer(redraw)
5063
5064 def selection_add(self, *items, run_binding: bool = True, redraw: bool = True) -> Sheet:
5065 to_open = []
5066 quick_displayed_check = set(self.MT.displayed_rows)
5067 for item in filter(self.RI.rns.__contains__, unpack(items)):
5068 if self.RI.rns[item] not in quick_displayed_check and self.RI.iid_parent(item):
5069 to_open.extend(list(self.RI.get_iid_ancestors(item)))
5070 if to_open:
5071 self.show_rows(
5072 rows=self._tree_open(to_open),
5073 redraw=False,
5074 deselect_all=False,
5075 )
5076 for startr, endr in consecutive_ranges(
5077 sorted(
5078 bisect_left(
5079 self.MT.displayed_rows,
5080 self.RI.rns[item],
5081 )
5082 for item in filter(self.RI.rns.__contains__, unpack(items))
5083 )
5084 ):
5085 self.MT.create_selection_box(
5086 startr,
5087 0,
5088 endr,
5089 len(self.MT.col_positions) - 1,
5090 "rows",
5091 set_current=True,
5092 ext=True,
5093 )
5094 if run_binding:
5095 self.MT.run_selection_binding("rows")
5096 return self.set_refresh_timer(redraw)
5097
5098 def selection_remove(self, *items, redraw: bool = True) -> Sheet:
5099 for item in unpack(items):
5100 if item not in self.RI.rns:
5101 continue
5102 try:
5103 self.deselect(bisect_left(self.MT.displayed_rows, self.RI.rns[item]), redraw=False)
5104 except Exception:
5105 continue
5106 return self.set_refresh_timer(redraw)
5107
5108 def selection_toggle(self, *items, redraw: bool = True) -> Sheet:
5109 selected = {self.MT._row_index[self.displayed_row_to_data(rn)].iid for rn in self.get_selected_rows()}
5110 add = []
5111 remove = []
5112 for item in unpack(items):
5113 if item in self.RI.rns:
5114 if item in selected:
5115 remove.append(item)
5116 else:
5117 add.append(item)
5118 self.selection_remove(*remove, redraw=False)
5119 self.selection_add(*add, redraw=False)
5120 return self.set_refresh_timer(redraw)
5121
5122 def descendants(self, item: str, check_open: bool = False) -> Generator[str]:
5123 return self.RI.get_iid_descendants(item, check_open=check_open)
5124
5125 # Functions not in docs
5126
5127 def event_generate(self, *args, **kwargs) -> None:
5128 self.MT.event_generate(*args, **kwargs)
5129
5130 def emit_event(
5131 self,
5132 event: str,
5133 data: EventDataDict | None = None,
5134 ) -> None:
5135 if data is None:
5136 data = EventDataDict()
5137 data["sheetname"] = self.name
5138 self.last_event_data = data
5139 for func in self.bound_events[event]:
5140 func(data)
5141
5142 def set_refresh_timer(
5143 self,
5144 redraw: bool = True,
5145 index: bool = True,
5146 header: bool = True,
5147 ) -> Sheet:
5148 if redraw and self.after_redraw_id is None:
5149 self.after_redraw_id = self.after(
5150 self.after_redraw_time_ms, lambda: self.after_redraw(index=index, header=header)
5151 )
5152 return self
5153
5154 def after_redraw(self, index: bool = True, header: bool = True) -> None:
5155 self.MT.main_table_redraw_grid_and_text(redraw_header=header, redraw_row_index=index)
5156 self.after_redraw_id = None
5157
5158 def del_options_using_span(
5159 self,
5160 span: Span,
5161 key: str,
5162 redraw: bool = True,
5163 ) -> Span:
5164 rows, cols = self.ranges_from_span(span)
5165 table, index, header = span.table, span.index, span.header
5166 # index header
5167 if header and span.kind in ("cell", "column"):
5168 self.CH.hide_dropdown_window()
5169 del_from_options(self.CH.cell_options, key, cols)
5170 if index and span.kind in ("cell", "row"):
5171 self.RI.hide_dropdown_window()
5172 del_from_options(self.RI.cell_options, key, rows)
5173 # table
5174 if table and span.kind == "cell":
5175 del_from_options(self.MT.cell_options, key, product(rows, cols))
5176 elif table and span.kind == "row":
5177 del_from_options(self.MT.row_options, key, rows)
5178 elif table and span.kind == "column":
5179 del_from_options(self.MT.col_options, key, cols)
5180 self.set_refresh_timer(redraw)
5181 return span
5182
5183 # ########## TABLE ##########
5184
5185 def del_cell_options_dropdown(self, datarn: int, datacn: int) -> None:
5186 self.MT.hide_dropdown_window()
5187 if (datarn, datacn) in self.MT.cell_options and "dropdown" in self.MT.cell_options[(datarn, datacn)]:
5188 del self.MT.cell_options[(datarn, datacn)]["dropdown"]
5189
5190 def del_cell_options_checkbox(self, datarn: int, datacn: int) -> None:
5191 if (datarn, datacn) in self.MT.cell_options and "checkbox" in self.MT.cell_options[(datarn, datacn)]:
5192 del self.MT.cell_options[(datarn, datacn)]["checkbox"]
5193
5194 def del_cell_options_dropdown_and_checkbox(self, datarn: int, datacn: int) -> None:
5195 self.del_cell_options_dropdown(datarn, datacn)
5196 self.del_cell_options_checkbox(datarn, datacn)
5197
5198 def del_row_options_dropdown(self, datarn: int) -> None:
5199 self.MT.hide_dropdown_window()
5200 if datarn in self.MT.row_options and "dropdown" in self.MT.row_options[datarn]:
5201 del self.MT.row_options[datarn]["dropdown"]
5202
5203 def del_row_options_checkbox(self, datarn: int) -> None:
5204 if datarn in self.MT.row_options and "checkbox" in self.MT.row_options[datarn]:
5205 del self.MT.row_options[datarn]["checkbox"]
5206
5207 def del_row_options_dropdown_and_checkbox(self, datarn: int) -> None:
5208 self.del_row_options_dropdown(datarn)
5209 self.del_row_options_checkbox(datarn)
5210
5211 def del_column_options_dropdown(self, datacn: int) -> None:
5212 self.MT.hide_dropdown_window()
5213 if datacn in self.MT.col_options and "dropdown" in self.MT.col_options[datacn]:
5214 del self.MT.col_options[datacn]["dropdown"]
5215
5216 def del_column_options_checkbox(self, datacn: int) -> None:
5217 if datacn in self.MT.col_options and "checkbox" in self.MT.col_options[datacn]:
5218 del self.MT.col_options[datacn]["checkbox"]
5219
5220 def del_column_options_dropdown_and_checkbox(self, datacn: int) -> None:
5221 self.del_column_options_dropdown(datacn)
5222 self.del_column_options_checkbox(datacn)
5223
5224 # ########## INDEX ##########
5225
5226 def del_index_cell_options_dropdown(self, datarn: int) -> None:
5227 self.RI.hide_dropdown_window()
5228 if datarn in self.RI.cell_options and "dropdown" in self.RI.cell_options[datarn]:
5229 del self.RI.cell_options[datarn]["dropdown"]
5230
5231 def del_index_cell_options_checkbox(self, datarn: int) -> None:
5232 if datarn in self.RI.cell_options and "checkbox" in self.RI.cell_options[datarn]:
5233 del self.RI.cell_options[datarn]["checkbox"]
5234
5235 def del_index_cell_options_dropdown_and_checkbox(self, datarn: int) -> None:
5236 self.del_index_cell_options_dropdown(datarn)
5237 self.del_index_cell_options_checkbox(datarn)
5238
5239 # ########## HEADER ##########
5240
5241 def del_header_cell_options_dropdown(self, datacn: int) -> None:
5242 self.CH.hide_dropdown_window()
5243 if datacn in self.CH.cell_options and "dropdown" in self.CH.cell_options[datacn]:
5244 del self.CH.cell_options[datacn]["dropdown"]
5245
5246 def del_header_cell_options_checkbox(self, datacn: int) -> None:
5247 if datacn in self.CH.cell_options and "checkbox" in self.CH.cell_options[datacn]:
5248 del self.CH.cell_options[datacn]["checkbox"]
5249
5250 def del_header_cell_options_dropdown_and_checkbox(self, datacn: int) -> None:
5251 self.del_header_cell_options_dropdown(datacn)
5252 self.del_header_cell_options_checkbox(datacn)
5253
5254 # ########## OLD FUNCTIONS ##########
5255
5256 def get_cell_data(self, r: int, c: int, get_displayed: bool = False) -> Any:
5257 if get_displayed:
5258 return self.MT.cell_str(r, c, get_displayed=True)
5259 else:
5260 return self.MT.get_cell_data(r, c)
5261
5262 def get_row_data(
5263 self,
5264 r: int,
5265 get_displayed: bool = False,
5266 get_index: bool = False,
5267 get_index_displayed: bool = True,
5268 only_columns: int | Iterator[int] | None = None,
5269 ) -> list[Any]:
5270 if only_columns is not None:
5271 if isinstance(only_columns, int):
5272 only_columns = (only_columns,)
5273 elif not is_iterable(only_columns):
5274 raise ValueError(tksheet_type_error("only_columns", ["int", "iterable", "None"], only_columns))
5275 if r >= self.MT.total_data_rows():
5276 raise IndexError(f"Row #{r} is out of range.")
5277
5278 if r >= len(self.MT.data):
5279 total_data_cols = self.MT.total_data_cols()
5280 self.MT.fix_data_len(r, total_data_cols - 1)
5281
5282 iterable = only_columns if only_columns is not None else range(len(self.MT.data[r]))
5283 f = partial(self.MT.cell_str, get_displayed=True) if get_displayed else self.MT.get_cell_data
5284 row = [self.RI.get_cell_data(r, get_displayed=get_index_displayed)] if get_index else []
5285 row.extend(f(r, c) for c in iterable)
5286 return row
5287
5288 def get_column_data(
5289 self,
5290 c: int,
5291 get_displayed: bool = False,
5292 get_header: bool = False,
5293 get_header_displayed: bool = True,
5294 only_rows: int | Iterator[int] | None = None,
5295 ) -> list[Any]:
5296 if only_rows is not None:
5297 if isinstance(only_rows, int):
5298 only_rows = (only_rows,)
5299 elif not is_iterable(only_rows):
5300 raise ValueError(tksheet_type_error("only_rows", ["int", "iterable", "None"], only_rows))
5301 iterable = only_rows if only_rows is not None else range(len(self.MT.data))
5302 f = partial(self.MT.cell_str, get_displayed=True) if get_displayed else self.MT.get_cell_data
5303 col = [self.CH.get_cell_data(c, get_displayed=get_header_displayed)] if get_header else []
5304 col.extend(f(r, c) for r in iterable)
5305 return col
5306
5307 def get_sheet_data(
5308 self,
5309 get_displayed: bool = False,
5310 get_header: bool = False,
5311 get_index: bool = False,
5312 get_header_displayed: bool = True,
5313 get_index_displayed: bool = True,
5314 only_rows: Iterator[int] | int | None = None,
5315 only_columns: Iterator[int] | int | None = None,
5316 ) -> list[list[Any]]:
5317 if only_rows is not None:
5318 if isinstance(only_rows, int):
5319 only_rows = (only_rows,)
5320 elif not is_iterable(only_rows):
5321 raise ValueError(tksheet_type_error("only_rows", ["int", "iterable", "None"], only_rows))
5322 if only_columns is not None:
5323 if isinstance(only_columns, int):
5324 only_columns = (only_columns,)
5325 elif not is_iterable(only_columns):
5326 raise ValueError(tksheet_type_error("only_columns", ["int", "iterable", "None"], only_columns))
5327
5328 if get_header:
5329 maxlen = len(self.MT._headers) if isinstance(self.MT._headers, (list, tuple)) else 0
5330 data = []
5331 for rn in only_rows if only_rows is not None else range(len(self.MT.data)):
5332 r = self.get_row_data(rn, get_displayed=get_displayed, only_columns=only_columns)
5333 if len(r) > maxlen:
5334 maxlen = len(r)
5335 if get_index:
5336 row = [self.RI.get_cell_data(rn, get_displayed=get_index_displayed)]
5337 row.extend(r)
5338 data.append(row)
5339 else:
5340 data.append(r)
5341 iterable = only_columns if only_columns is not None else range(maxlen)
5342 header_row = [""] if get_index else []
5343 header_row.extend(self.CH.get_cell_data(cn, get_displayed=get_header_displayed) for cn in iterable)
5344 result = [header_row]
5345 result.extend(data)
5346 return result
5347
5348 else:
5349 iterable = only_rows if only_rows is not None else range(len(self.MT.data))
5350 return [
5351 self.get_row_data(
5352 rn,
5353 get_displayed=get_displayed,
5354 get_index=get_index,
5355 get_index_displayed=get_index_displayed,
5356 only_columns=only_columns,
5357 )
5358 for rn in iterable
5359 ]
5360
5361 def yield_sheet_rows(
5362 self,
5363 get_displayed: bool = False,
5364 get_header: bool = False,
5365 get_index: bool = False,
5366 get_index_displayed: bool = True,
5367 get_header_displayed: bool = True,
5368 only_rows: int | Iterator[int] | None = None,
5369 only_columns: int | Iterator[int] | None = None,
5370 ) -> Generator[list[Any]]:
5371 if only_rows is not None:
5372 if isinstance(only_rows, int):
5373 only_rows = (only_rows,)
5374 elif not is_iterable(only_rows):
5375 raise ValueError(tksheet_type_error("only_rows", ["int", "iterable", "None"], only_rows))
5376 if only_columns is not None:
5377 if isinstance(only_columns, int):
5378 only_columns = (only_columns,)
5379 elif not is_iterable(only_columns):
5380 raise ValueError(tksheet_type_error("only_columns", ["int", "iterable", "None"], only_columns))
5381
5382 if get_header:
5383 iterable = only_columns if only_columns is not None else range(self.MT.total_data_cols())
5384 header_row = [""] if get_index else []
5385 header_row.extend(self.CH.get_cell_data(c, get_displayed=get_header_displayed) for c in iterable)
5386 yield header_row
5387
5388 iterable = only_rows if only_rows is not None else range(len(self.MT.data))
5389 yield from (
5390 self.get_row_data(
5391 r,
5392 get_displayed=get_displayed,
5393 get_index=get_index,
5394 get_index_displayed=get_index_displayed,
5395 only_columns=only_columns,
5396 )
5397 for r in iterable
5398 )
5399
5400 def get_header_data(self, c: int, get_displayed: bool = False):
5401 return self.CH.get_cell_data(datacn=c, get_displayed=get_displayed)
5402
5403 def get_index_data(self, r: int, get_displayed: bool = False):
5404 return self.RI.get_cell_data(datarn=r, get_displayed=get_displayed)
5405
5406 def data_reference(
5407 self,
5408 newdataref=None,
5409 reset_col_positions: bool = True,
5410 reset_row_positions: bool = True,
5411 redraw: bool = True,
5412 ) -> Any:
5413 self.set_refresh_timer(redraw)
5414 return self.MT.data_reference(newdataref, reset_col_positions, reset_row_positions)
5415
5416 def set_cell_data(
5417 self,
5418 r: int,
5419 c: int,
5420 value: Any = "",
5421 redraw: bool = True,
5422 keep_formatting: bool = True,
5423 ) -> Sheet:
5424 if not keep_formatting:
5425 self.MT.delete_cell_format(r, c, clear_values=False)
5426 self.MT.set_cell_data(r, c, value)
5427 return self.set_refresh_timer(redraw)
5428
5429 def set_row_data(
5430 self,
5431 r: int,
5432 values: Sequence[Any] = [],
5433 add_columns: bool = True,
5434 redraw: bool = True,
5435 keep_formatting: bool = True,
5436 ) -> Sheet:
5437 if r >= len(self.MT.data):
5438 raise Exception("Row number is out of range")
5439 if not keep_formatting:
5440 self.MT.delete_row_format(r, clear_values=False)
5441 maxidx = len(self.MT.data[r]) - 1
5442 if not values:
5443 self.MT.data[r] = self.MT.get_empty_row_seq(r, len(self.MT.data[r]))
5444 else:
5445 if add_columns:
5446 for c, v in enumerate(values):
5447 if c > maxidx:
5448 self.MT.data[r].append(v)
5449 if self.MT.all_columns_displayed:
5450 self.MT.insert_col_positions()
5451 else:
5452 self.set_cell_data(r=r, c=c, value=v, redraw=False, keep_formatting=keep_formatting)
5453 else:
5454 for c, v in enumerate(values):
5455 if c > maxidx:
5456 self.MT.data[r].append(v)
5457 else:
5458 self.set_cell_data(r=r, c=c, value=v, redraw=False, keep_formatting=keep_formatting)
5459 return self.set_refresh_timer(redraw)
5460
5461 def set_column_data(
5462 self,
5463 c: int,
5464 values: Sequence[Any] = [],
5465 add_rows: bool = True,
5466 redraw: bool = True,
5467 keep_formatting: bool = True,
5468 ) -> Sheet:
5469 if not keep_formatting:
5470 self.MT.delete_column_format(c, clear_values=False)
5471 if add_rows:
5472 maxidx = len(self.MT.data) - 1
5473 total_cols = None
5474 height = self.MT.get_default_row_height()
5475 for rn, v in enumerate(values):
5476 if rn > maxidx:
5477 if total_cols is None:
5478 total_cols = self.MT.total_data_cols()
5479 self.MT.fix_data_len(rn, total_cols - 1)
5480 if self.MT.all_rows_displayed:
5481 self.MT.insert_row_positions(heights=height)
5482 maxidx += 1
5483 if c >= len(self.MT.data[rn]):
5484 self.MT.fix_row_len(rn, c)
5485 self.set_cell_data(r=rn, c=c, value=v, redraw=False, keep_formatting=keep_formatting)
5486 else:
5487 for rn, v in enumerate(values):
5488 if c >= len(self.MT.data[rn]):
5489 self.MT.fix_row_len(rn, c)
5490 self.set_cell_data(r=rn, c=c, value=v, redraw=False, keep_formatting=keep_formatting)
5491 return self.set_refresh_timer(redraw)
5492
5493 def readonly_rows(
5494 self,
5495 rows: list[int] | int,
5496 readonly: bool = True,
5497 redraw: bool = False,
5498 ) -> Sheet:
5499 if isinstance(rows, int):
5500 rows = [rows]
5501 if not readonly:
5502 for r in rows:
5503 if r in self.MT.row_options and "readonly" in self.MT.row_options[r]:
5504 del self.MT.row_options[r]["readonly"]
5505 else:
5506 for r in rows:
5507 if r not in self.MT.row_options:
5508 self.MT.row_options[r] = {}
5509 self.MT.row_options[r]["readonly"] = True
5510 return self.set_refresh_timer(redraw)
5511
5512 def readonly_columns(
5513 self,
5514 columns: list[int] | int,
5515 readonly: bool = True,
5516 redraw: bool = False,
5517 ) -> Sheet:
5518 if isinstance(columns, int):
5519 columns = [columns]
5520 if not readonly:
5521 for c in columns:
5522 if c in self.MT.col_options and "readonly" in self.MT.col_options[c]:
5523 del self.MT.col_options[c]["readonly"]
5524 else:
5525 for c in columns:
5526 if c not in self.MT.col_options:
5527 self.MT.col_options[c] = {}
5528 self.MT.col_options[c]["readonly"] = True
5529 return self.set_refresh_timer(redraw)
5530
5531 def readonly_cells(
5532 self,
5533 row: int = 0,
5534 column: int = 0,
5535 cells: list[tuple[int, int]] | None = None,
5536 readonly: bool = True,
5537 redraw: bool = False,
5538 ) -> Sheet:
5539 if not readonly:
5540 if cells:
5541 for r, c in cells:
5542 if (r, c) in self.MT.cell_options and "readonly" in self.MT.cell_options[(r, c)]:
5543 del self.MT.cell_options[(r, c)]["readonly"]
5544 else:
5545 if (
5546 row,
5547 column,
5548 ) in self.MT.cell_options and "readonly" in self.MT.cell_options[(row, column)]:
5549 del self.MT.cell_options[(row, column)]["readonly"]
5550 else:
5551 if cells:
5552 for r, c in cells:
5553 if (r, c) not in self.MT.cell_options:
5554 self.MT.cell_options[(r, c)] = {}
5555 self.MT.cell_options[(r, c)]["readonly"] = True
5556 else:
5557 if (row, column) not in self.MT.cell_options:
5558 self.MT.cell_options[(row, column)] = {}
5559 self.MT.cell_options[(row, column)]["readonly"] = True
5560 return self.set_refresh_timer(redraw)
5561
5562 def readonly_header(
5563 self,
5564 columns: list[int],
5565 readonly: bool = True,
5566 redraw: bool = False,
5567 ) -> Sheet:
5568 self.CH.readonly_header(columns=columns, readonly=readonly)
5569 return self.set_refresh_timer(redraw)
5570
5571 def readonly_index(
5572 self,
5573 rows: list[int],
5574 readonly: bool = True,
5575 redraw: bool = False,
5576 ) -> Sheet:
5577 self.RI.readonly_index(rows=rows, readonly=readonly)
5578 return self.set_refresh_timer(redraw)
5579
5580 def dehighlight_rows(
5581 self,
5582 rows: list[int] | Literal["all"],
5583 redraw: bool = True,
5584 ) -> Sheet:
5585 if isinstance(rows, int):
5586 rows = [rows]
5587 if not rows or rows == "all":
5588 for r in self.MT.row_options:
5589 if "highlight" in self.MT.row_options[r]:
5590 del self.MT.row_options[r]["highlight"]
5591
5592 for r in self.RI.cell_options:
5593 if "highlight" in self.RI.cell_options[r]:
5594 del self.RI.cell_options[r]["highlight"]
5595 else:
5596 for r in rows:
5597 with suppress(Exception):
5598 del self.MT.row_options[r]["highlight"]
5599 with suppress(Exception):
5600 del self.RI.cell_options[r]["highlight"]
5601 return self.set_refresh_timer(redraw)
5602
5603 def dehighlight_columns(
5604 self,
5605 columns: list[int] | Literal["all"],
5606 redraw: bool = True,
5607 ) -> Sheet:
5608 if isinstance(columns, int):
5609 columns = [columns]
5610 if not columns or columns == "all":
5611 for c in self.MT.col_options:
5612 if "highlight" in self.MT.col_options[c]:
5613 del self.MT.col_options[c]["highlight"]
5614
5615 for c in self.CH.cell_options:
5616 if "highlight" in self.CH.cell_options[c]:
5617 del self.CH.cell_options[c]["highlight"]
5618 else:
5619 for c in columns:
5620 with suppress(Exception):
5621 del self.MT.col_options[c]["highlight"]
5622 with suppress(Exception):
5623 del self.CH.cell_options[c]["highlight"]
5624 return self.set_refresh_timer(redraw)
5625
5626 def highlight_rows(
5627 self,
5628 rows: Iterator[int] | int,
5629 bg: None | str = None,
5630 fg: None | str = None,
5631 highlight_index: bool = True,
5632 redraw: bool = True,
5633 end_of_screen: bool = False,
5634 overwrite: bool = True,
5635 ) -> Sheet:
5636 if bg is None and fg is None:
5637 return
5638 for r in (rows,) if isinstance(rows, int) else rows:
5639 add_highlight(self.MT.row_options, r, bg, fg, end_of_screen, overwrite)
5640 if highlight_index:
5641 self.highlight_cells(cells=rows, canvas="index", bg=bg, fg=fg, redraw=False)
5642 return self.set_refresh_timer(redraw)
5643
5644 def highlight_columns(
5645 self,
5646 columns: Iterator[int] | int,
5647 bg: bool | None | str = False,
5648 fg: bool | None | str = False,
5649 highlight_header: bool = True,
5650 redraw: bool = True,
5651 overwrite: bool = True,
5652 ) -> Sheet:
5653 if bg is False and fg is False:
5654 return
5655 for c in (columns,) if isinstance(columns, int) else columns:
5656 add_highlight(self.MT.col_options, c, bg, fg, None, overwrite)
5657 if highlight_header:
5658 self.highlight_cells(cells=columns, canvas="header", bg=bg, fg=fg, redraw=False)
5659 return self.set_refresh_timer(redraw)
5660
5661 def highlight_cells(
5662 self,
5663 row: int | Literal["all"] = 0,
5664 column: int | Literal["all"] = 0,
5665 cells: list[tuple[int, int]] | None = None,
5666 canvas: Literal["table", "index", "header"] = "table",
5667 bg: bool | None | str = False,
5668 fg: bool | None | str = False,
5669 redraw: bool = True,
5670 overwrite: bool = True,
5671 ) -> Sheet:
5672 if bg is False and fg is False:
5673 return
5674 if canvas == "table":
5675 if cells:
5676 for r_, c_ in cells:
5677 add_highlight(self.MT.cell_options, (r_, c_), bg, fg, None, overwrite)
5678 else:
5679 if (
5680 isinstance(row, str)
5681 and row.lower() == "all"
5682 and isinstance(column, str)
5683 and column.lower() == "all"
5684 ):
5685 totalrows, totalcols = self.MT.total_data_rows(), self.MT.total_data_cols()
5686 for r_ in range(totalrows):
5687 for c_ in range(totalcols):
5688 add_highlight(self.MT.cell_options, (r_, c_), bg, fg, None, overwrite)
5689 elif isinstance(row, str) and row.lower() == "all" and isinstance(column, int):
5690 for r_ in range(self.MT.total_data_rows()):
5691 add_highlight(self.MT.cell_options, (r_, column), bg, fg, None, overwrite)
5692 elif isinstance(column, str) and column.lower() == "all" and isinstance(row, int):
5693 for c_ in range(self.MT.total_data_cols()):
5694 add_highlight(self.MT.cell_options, (row, c_), bg, fg, None, overwrite)
5695 elif isinstance(row, int) and isinstance(column, int):
5696 add_highlight(self.MT.cell_options, (row, column), bg, fg, None, overwrite)
5697 elif canvas in ("row_index", "index"):
5698 if isinstance(cells, int):
5699 add_highlight(self.RI.cell_options, cells, bg, fg, None, overwrite)
5700 elif cells:
5701 for r_ in cells:
5702 add_highlight(self.RI.cell_options, r_, bg, fg, None, overwrite)
5703 else:
5704 add_highlight(self.RI.cell_options, row, bg, fg, None, overwrite)
5705 elif canvas == "header":
5706 if isinstance(cells, int):
5707 add_highlight(self.CH.cell_options, cells, bg, fg, None, overwrite)
5708 elif cells:
5709 for c_ in cells:
5710 add_highlight(self.CH.cell_options, c_, bg, fg, None, overwrite)
5711 else:
5712 add_highlight(self.CH.cell_options, column, bg, fg, None, overwrite)
5713 return self.set_refresh_timer(redraw)
5714
5715 def dehighlight_cells(
5716 self,
5717 row: int | Literal["all"] = 0,
5718 column: int = 0,
5719 cells: list[tuple[int, int]] | None = None,
5720 canvas: Literal["table", "row_index", "index", "header"] = "table",
5721 all_: bool = False,
5722 redraw: bool = True,
5723 ) -> Sheet:
5724 if row == "all" and canvas == "table":
5725 for k, v in self.MT.cell_options.items():
5726 if "highlight" in v:
5727 del self.MT.cell_options[k]["highlight"]
5728 elif row == "all" and canvas == "row_index":
5729 for k, v in self.RI.cell_options.items():
5730 if "highlight" in v:
5731 del self.RI.cell_options[k]["highlight"]
5732 elif row == "all" and canvas == "header":
5733 for k, v in self.CH.cell_options.items():
5734 if "highlight" in v:
5735 del self.CH.cell_options[k]["highlight"]
5736 if canvas == "table":
5737 if cells and not all_:
5738 for t in cells:
5739 try:
5740 del self.MT.cell_options[t]["highlight"]
5741 except Exception:
5742 continue
5743 elif not all_:
5744 if (
5745 row,
5746 column,
5747 ) in self.MT.cell_options and "highlight" in self.MT.cell_options[(row, column)]:
5748 del self.MT.cell_options[(row, column)]["highlight"]
5749 elif all_:
5750 for k in self.MT.cell_options:
5751 if "highlight" in self.MT.cell_options[k]:
5752 del self.MT.cell_options[k]["highlight"]
5753 elif canvas in ("row_index", "index"):
5754 if cells and not all_:
5755 for r in cells:
5756 try:
5757 del self.RI.cell_options[r]["highlight"]
5758 except Exception:
5759 continue
5760 elif not all_:
5761 if row in self.RI.cell_options and "highlight" in self.RI.cell_options[row]:
5762 del self.RI.cell_options[row]["highlight"]
5763 elif all_:
5764 for r in self.RI.cell_options:
5765 if "highlight" in self.RI.cell_options[r]:
5766 del self.RI.cell_options[r]["highlight"]
5767 elif canvas == "header":
5768 if cells and not all_:
5769 for c in cells:
5770 try:
5771 del self.CH.cell_options[c]["highlight"]
5772 except Exception:
5773 continue
5774 elif not all_:
5775 if column in self.CH.cell_options and "highlight" in self.CH.cell_options[column]:
5776 del self.CH.cell_options[column]["highlight"]
5777 elif all_:
5778 for c in self.CH.cell_options:
5779 if "highlight" in self.CH.cell_options[c]:
5780 del self.CH.cell_options[c]["highlight"]
5781 return self.set_refresh_timer(redraw)
5782
5783 def get_highlighted_cells(
5784 self,
5785 canvas: Literal["table", "row_index", "index", "header"] = "table",
5786 ) -> dict | None:
5787 if canvas == "table":
5788 return {k: v["highlight"] for k, v in self.MT.cell_options.items() if "highlight" in v}
5789 elif canvas in ("row_index", "index"):
5790 return {k: v["highlight"] for k, v in self.RI.cell_options.items() if "highlight" in v}
5791 elif canvas == "header":
5792 return {k: v["highlight"] for k, v in self.CH.cell_options.items() if "highlight" in v}
5793
5794 def align_cells(
5795 self,
5796 row: int = 0,
5797 column: int = 0,
5798 cells: list[tuple[int, int]] | dict[tuple[int, int], str] | None = None,
5799 align: str | None = "global",
5800 redraw: bool = True,
5801 ) -> Sheet:
5802 if isinstance(cells, dict):
5803 for k, v in cells.items():
5804 set_align(self.MT.cell_options, k, convert_align(v))
5805 elif cells:
5806 align = convert_align(align)
5807 for k in cells:
5808 set_align(self.MT.cell_options, k, align)
5809 else:
5810 set_align(self.MT.cell_options, (row, column), convert_align(align))
5811 return self.set_refresh_timer(redraw)
5812
5813 def align_rows(
5814 self,
5815 rows: list[int] | dict[int, str] | int,
5816 align: str | None = "global",
5817 align_index: bool = False,
5818 redraw: bool = True,
5819 ) -> Sheet:
5820 if isinstance(rows, dict):
5821 for k, v in rows.items():
5822 align = convert_align(v)
5823 set_align(self.MT.row_options, k, align)
5824 if align_index:
5825 set_align(self.RI.cell_options, k, align)
5826 elif is_iterable(rows):
5827 align = convert_align(align)
5828 for k in rows:
5829 set_align(self.MT.row_options, k, align)
5830 if align_index:
5831 set_align(self.RI.cell_options, k, align)
5832 elif isinstance(rows, int):
5833 set_align(self.MT.row_options, rows, convert_align(align))
5834 if align_index:
5835 set_align(self.RI.cell_options, rows, align)
5836 return self.set_refresh_timer(redraw)
5837
5838 def align_columns(
5839 self,
5840 columns: list[int] | dict[int, str] | int,
5841 align: str | None = "global",
5842 align_header: bool = False,
5843 redraw: bool = True,
5844 ) -> Sheet:
5845 if isinstance(columns, dict):
5846 for k, v in columns.items():
5847 align = convert_align(v)
5848 set_align(self.MT.col_options, k, align)
5849 if align_header:
5850 set_align(self.CH.cell_options, k, align)
5851 elif is_iterable(columns):
5852 align = convert_align(align)
5853 for k in columns:
5854 set_align(self.MT.col_options, k, align)
5855 if align_header:
5856 set_align(self.CH.cell_options, k, align)
5857 elif isinstance(columns, int):
5858 set_align(self.MT.col_options, columns, convert_align(align))
5859 if align_header:
5860 set_align(self.CH.cell_options, columns, align)
5861 return self.set_refresh_timer(redraw)
5862
5863 def align_header(
5864 self,
5865 columns: list[int] | dict[int, str] | int,
5866 align: str | None = "global",
5867 redraw: bool = True,
5868 ) -> Sheet:
5869 if isinstance(columns, dict):
5870 for k, v in columns.items():
5871 set_align(self.CH.cell_options, k, convert_align(v))
5872 elif is_iterable(columns):
5873 align = convert_align(align)
5874 for k in columns:
5875 set_align(self.CH.cell_options, k, align)
5876 elif isinstance(columns, int):
5877 set_align(self.CH.cell_options, columns, convert_align(align))
5878 return self.set_refresh_timer(redraw)
5879
5880 def align_index(
5881 self,
5882 rows: list[int] | dict[int, str] | int,
5883 align: str | None = "global",
5884 redraw: bool = True,
5885 ) -> Sheet:
5886 if isinstance(rows, dict):
5887 for k, v in rows.items():
5888 set_align(self.RI.cell_options, k, convert_align(v))
5889 elif is_iterable(rows):
5890 align = convert_align(align)
5891 for k in rows:
5892 set_align(self.RI.cell_options, k, align)
5893 elif isinstance(rows, int):
5894 set_align(self.RI.cell_options, rows, convert_align(align))
5895 return self.set_refresh_timer(redraw)
5896
5897 def get_cell_alignments(self) -> dict:
5898 return {(r, c): v["align"] for (r, c), v in self.MT.cell_options.items() if "align" in v}
5899
5900 def get_column_alignments(self) -> dict:
5901 return {c: v["align"] for c, v in self.MT.col_options.items() if "align" in v}
5902
5903 def get_row_alignments(self) -> dict:
5904 return {r: v["align"] for r, v in self.MT.row_options.items() if "align" in v}
5905
5906 def create_checkbox(
5907 self,
5908 r: int | Literal["all"] = 0,
5909 c: int | Literal["all"] = 0,
5910 *args,
5911 **kwargs,
5912 ) -> None:
5913 kwargs = get_checkbox_kwargs(*args, **kwargs)
5914 v = kwargs["checked"]
5915 d = get_checkbox_dict(**kwargs)
5916 if isinstance(r, str) and r.lower() == "all" and isinstance(c, int):
5917 for r_ in range(self.MT.total_data_rows()):
5918 self._create_checkbox(r_, c, v, d)
5919 elif isinstance(c, str) and c.lower() == "all" and isinstance(r, int):
5920 for c_ in range(self.MT.total_data_cols()):
5921 self._create_checkbox(r, c_, v, d)
5922 elif isinstance(r, str) and r.lower() == "all" and isinstance(c, str) and c.lower() == "all":
5923 totalcols = self.MT.total_data_cols()
5924 for r_ in range(self.MT.total_data_rows()):
5925 for c_ in range(totalcols):
5926 self._create_checkbox(r_, c_, v, d)
5927 elif isinstance(r, int) and isinstance(c, int):
5928 self._create_checkbox(r, c, v, d)
5929 self.set_refresh_timer(kwargs["redraw"])
5930
5931 def _create_checkbox(self, r: int, c: int, v: bool, d: dict) -> None:
5932 self.MT.delete_cell_format(r, c, clear_values=False)
5933 self.del_cell_options_dropdown_and_checkbox(r, c)
5934 add_to_options(self.MT.cell_options, (r, c), "checkbox", d)
5935 self.MT.set_cell_data(r, c, v)
5936
5937 def checkbox_cell(
5938 self,
5939 r: int | Literal["all"] = 0,
5940 c: int | Literal["all"] = 0,
5941 *args,
5942 **kwargs,
5943 ) -> None:
5944 self.create_checkbox(r=r, c=c, **get_checkbox_kwargs(*args, **kwargs))
5945
5946 def checkbox_row(
5947 self,
5948 r: Iterator[int] | int | Literal["all"] = 0,
5949 *args,
5950 **kwargs,
5951 ) -> None:
5952 kwargs = get_checkbox_kwargs(*args, **kwargs)
5953 d = get_checkbox_dict(**kwargs)
5954 if isinstance(r, str) and r.lower() == "all":
5955 for r_ in range(self.MT.total_data_rows()):
5956 self._checkbox_row(r_, kwargs["checked"], d)
5957 elif isinstance(r, int):
5958 self._checkbox_row(r, kwargs["checked"], d)
5959 elif is_iterable(r):
5960 for r_ in r:
5961 self._checkbox_row(r_, kwargs["checked"], d)
5962 self.set_refresh_timer(kwargs["redraw"])
5963
5964 def _checkbox_row(self, r: int, v: bool, d: dict) -> None:
5965 self.MT.delete_row_format(r, clear_values=False)
5966 self.del_row_options_dropdown_and_checkbox(r)
5967 add_to_options(self.MT.row_options, r, "checkbox", d)
5968 for c in range(self.MT.total_data_cols()):
5969 self.MT.set_cell_data(r, c, v)
5970
5971 def checkbox_column(
5972 self,
5973 c: Iterator[int] | int | Literal["all"] = 0,
5974 *args,
5975 **kwargs,
5976 ) -> None:
5977 kwargs = get_checkbox_kwargs(*args, **kwargs)
5978 d = get_checkbox_dict(**kwargs)
5979 if isinstance(c, str) and c.lower() == "all":
5980 for c in range(self.MT.total_data_cols()):
5981 self._checkbox_column(c, kwargs["checked"], d)
5982 elif isinstance(c, int):
5983 self._checkbox_column(c, kwargs["checked"], d)
5984 elif is_iterable(c):
5985 for c_ in c:
5986 self._checkbox_column(c_, kwargs["checked"], d)
5987 self.set_refresh_timer(kwargs["redraw"])
5988
5989 def _checkbox_column(self, c: int, v: bool, d: dict) -> None:
5990 self.MT.delete_column_format(c, clear_values=False)
5991 self.del_column_options_dropdown_and_checkbox(c)
5992 add_to_options(self.MT.col_options, c, "checkbox", d)
5993 for r in range(self.MT.total_data_rows()):
5994 self.MT.set_cell_data(r, c, v)
5995
5996 def create_header_checkbox(
5997 self,
5998 c: Iterator[int] | int | Literal["all"] = 0,
5999 *args,
6000 **kwargs,
6001 ) -> None:
6002 kwargs = get_checkbox_kwargs(*args, **kwargs)
6003 d = get_checkbox_dict(**kwargs)
6004 if isinstance(c, str) and c.lower() == "all":
6005 for c_ in range(self.MT.total_data_cols()):
6006 self._create_header_checkbox(c_, kwargs["checked"], d)
6007 elif isinstance(c, int):
6008 self._create_header_checkbox(c, kwargs["checked"], d)
6009 elif is_iterable(c):
6010 for c_ in c:
6011 self._create_header_checkbox(c_, kwargs["checked"], d)
6012 self.set_refresh_timer(kwargs["redraw"])
6013
6014 def _create_header_checkbox(self, c: int, v: bool, d: dict) -> None:
6015 self.del_header_cell_options_dropdown_and_checkbox(c)
6016 add_to_options(self.CH.cell_options, c, "checkbox", d)
6017 self.CH.set_cell_data(c, v)
6018
6019 def create_index_checkbox(
6020 self,
6021 r: Iterator[int] | int | Literal["all"] = 0,
6022 *args,
6023 **kwargs,
6024 ) -> None:
6025 kwargs = get_checkbox_kwargs(*args, **kwargs)
6026 d = get_checkbox_dict(**kwargs)
6027 if isinstance(r, str) and r.lower() == "all":
6028 for r_ in range(self.MT.total_data_rows()):
6029 self._create_index_checkbox(r_, kwargs["checked"], d)
6030 elif isinstance(r, int):
6031 self._create_index_checkbox(r, kwargs["checked"], d)
6032 elif is_iterable(r):
6033 for r_ in r:
6034 self._create_index_checkbox(r_, kwargs["checked"], d)
6035 self.set_refresh_timer(kwargs["redraw"])
6036
6037 def _create_index_checkbox(self, r: int, v: bool, d: dict) -> None:
6038 self.del_index_cell_options_dropdown_and_checkbox(r)
6039 add_to_options(self.RI.cell_options, r, "checkbox", d)
6040 self.RI.set_cell_data(r, v)
6041
6042 def delete_checkbox(
6043 self,
6044 r: int | Literal["all"] = 0,
6045 c: int | Literal["all"] = 0,
6046 ) -> None:
6047 if isinstance(r, str) and r.lower() == "all" and isinstance(c, int):
6048 for r_, _ in self.MT.cell_options:
6049 if "checkbox" in self.MT.cell_options[(r_, c)]:
6050 self.del_cell_options_checkbox(r_, c)
6051 elif isinstance(c, str) and c.lower() == "all" and isinstance(r, int):
6052 for _, c_ in self.MT.cell_options:
6053 if "checkbox" in self.MT.cell_options[(r, c_)]:
6054 self.del_cell_options_checkbox(r, c_)
6055 elif isinstance(r, str) and r.lower() == "all" and isinstance(c, str) and c.lower() == "all":
6056 for r_, c_ in self.MT.cell_options:
6057 if "checkbox" in self.MT.cell_options[(r_, c_)]:
6058 self.del_cell_options_checkbox(r_, c_)
6059 elif isinstance(r, int) and isinstance(c, int):
6060 self.del_cell_options_checkbox(r, c)
6061
6062 def delete_cell_checkbox(
6063 self,
6064 r: int | Literal["all"] = 0,
6065 c: int | Literal["all"] = 0,
6066 ) -> None:
6067 self.delete_checkbox(r, c)
6068
6069 def delete_row_checkbox(
6070 self,
6071 r: Iterator[int] | int | Literal["all"] = 0,
6072 ) -> None:
6073 if isinstance(r, str) and r.lower() == "all":
6074 for r_ in self.MT.row_options:
6075 self.del_table_row_options_checkbox(r_)
6076 elif isinstance(r, int):
6077 self.del_table_row_options_checkbox(r)
6078 elif is_iterable(r):
6079 for r_ in r:
6080 self.del_table_row_options_checkbox(r_)
6081
6082 def delete_column_checkbox(
6083 self,
6084 c: Iterator[int] | int | Literal["all"] = 0,
6085 ) -> None:
6086 if isinstance(c, str) and c.lower() == "all":
6087 for c_ in self.MT.col_options:
6088 self.del_table_column_options_checkbox(c_)
6089 elif isinstance(c, int):
6090 self.del_table_column_options_checkbox(c)
6091 elif is_iterable(c):
6092 for c_ in c:
6093 self.del_table_column_options_checkbox(c_)
6094
6095 def delete_header_checkbox(
6096 self,
6097 c: Iterator[int] | int | Literal["all"] = 0,
6098 ) -> None:
6099 if isinstance(c, str) and c.lower() == "all":
6100 for c_ in self.CH.cell_options:
6101 if "checkbox" in self.CH.cell_options[c_]:
6102 self.del_header_cell_options_checkbox(c_)
6103 if isinstance(c, int):
6104 self.del_header_cell_options_checkbox(c)
6105 elif is_iterable(c):
6106 for c_ in c:
6107 self.del_header_cell_options_checkbox(c_)
6108
6109 def delete_index_checkbox(
6110 self,
6111 r: Iterator[int] | int | Literal["all"] = 0,
6112 ) -> None:
6113 if isinstance(r, str) and r.lower() == "all":
6114 for r_ in self.RI.cell_options:
6115 if "checkbox" in self.RI.cell_options[r_]:
6116 self.del_index_cell_options_checkbox(r_)
6117 if isinstance(r, int):
6118 self.del_index_cell_options_checkbox(r)
6119 elif is_iterable(r):
6120 for r_ in r:
6121 self.del_index_cell_options_checkbox(r_)
6122
6123 def click_header_checkbox(self, c: int, checked: bool | None = None) -> Sheet:
6124 kwargs = self.CH.get_cell_kwargs(c, key="checkbox")
6125 if kwargs:
6126 if not isinstance(self.MT._headers[c], bool):
6127 if checked is None:
6128 self.MT._headers[c] = False
6129 else:
6130 self.MT._headers[c] = bool(checked)
6131 else:
6132 self.MT._headers[c] = not self.MT._headers[c]
6133 return self
6134
6135 def click_index_checkbox(self, r: int, checked: bool | None = None) -> Sheet:
6136 kwargs = self.RI.get_cell_kwargs(r, key="checkbox")
6137 if kwargs:
6138 if not isinstance(self.MT._row_index[r], bool):
6139 if checked is None:
6140 self.MT._row_index[r] = False
6141 else:
6142 self.MT._row_index[r] = bool(checked)
6143 else:
6144 self.MT._row_index[r] = not self.MT._row_index[r]
6145 return self
6146
6147 def get_checkboxes(self) -> dict:
6148 return {
6149 **{k: v["checkbox"] for k, v in self.MT.cell_options.items() if "checkbox" in v},
6150 **{k: v["checkbox"] for k, v in self.MT.row_options.items() if "checkbox" in v},
6151 **{k: v["checkbox"] for k, v in self.MT.col_options.items() if "checkbox" in v},
6152 }
6153
6154 def get_header_checkboxes(self) -> dict:
6155 return {k: v["checkbox"] for k, v in self.CH.cell_options.items() if "checkbox" in v}
6156
6157 def get_index_checkboxes(self) -> dict:
6158 return {k: v["checkbox"] for k, v in self.RI.cell_options.items() if "checkbox" in v}
6159
6160 def create_dropdown(
6161 self,
6162 r: int | Literal["all"] = 0,
6163 c: int | Literal["all"] = 0,
6164 *args,
6165 **kwargs,
6166 ) -> Sheet:
6167 kwargs = get_dropdown_kwargs(*args, **kwargs)
6168 d = get_dropdown_dict(**kwargs)
6169 v = kwargs["set_value"] if kwargs["set_value"] is not None else kwargs["values"][0] if kwargs["values"] else ""
6170 if isinstance(r, str) and r.lower() == "all" and isinstance(c, int):
6171 for r_ in range(self.MT.total_data_rows()):
6172 self._create_dropdown(r_, c, v, d)
6173 elif isinstance(c, str) and c.lower() == "all" and isinstance(r, int):
6174 for c_ in range(self.MT.total_data_cols()):
6175 self._create_dropdown(r, c_, v, d)
6176 elif isinstance(r, str) and r.lower() == "all" and isinstance(c, str) and c.lower() == "all":
6177 totalcols = self.MT.total_data_cols()
6178 for r_ in range(self.MT.total_data_rows()):
6179 for c_ in range(totalcols):
6180 self._create_dropdown(r_, c_, v, d)
6181 elif isinstance(r, int) and isinstance(c, int):
6182 self._create_dropdown(r, c, v, d)
6183 return self.set_refresh_timer(kwargs["redraw"])
6184
6185 def _create_dropdown(self, r: int, c: int, v: Any, d: dict) -> None:
6186 self.del_cell_options_dropdown_and_checkbox(r, c)
6187 add_to_options(self.MT.cell_options, (r, c), "dropdown", d)
6188 self.MT.set_cell_data(r, c, v)
6189
6190 def dropdown_cell(
6191 self,
6192 r: int | Literal["all"] = 0,
6193 c: int | Literal["all"] = 0,
6194 *args,
6195 **kwargs,
6196 ) -> Sheet:
6197 return self.create_dropdown(r=r, c=c, **get_dropdown_kwargs(*args, **kwargs))
6198
6199 def dropdown_row(
6200 self,
6201 r: Iterator[int] | int | Literal["all"] = 0,
6202 *args,
6203 **kwargs,
6204 ) -> Sheet:
6205 kwargs = get_dropdown_kwargs(*args, **kwargs)
6206 d = get_dropdown_dict(**kwargs)
6207 v = kwargs["set_value"] if kwargs["set_value"] is not None else kwargs["values"][0] if kwargs["values"] else ""
6208 if isinstance(r, str) and r.lower() == "all":
6209 for r_ in range(self.MT.total_data_rows()):
6210 self._dropdown_row(r_, v, d)
6211 elif isinstance(r, int):
6212 self._dropdown_row(r, v, d)
6213 elif is_iterable(r):
6214 for r_ in r:
6215 self._dropdown_row(r_, v, d)
6216 return self.set_refresh_timer(kwargs["redraw"])
6217
6218 def _dropdown_row(self, r: int, v: Any, d: dict) -> None:
6219 self.del_row_options_dropdown_and_checkbox(r)
6220 add_to_options(self.MT.row_options, r, "dropdown", d)
6221 for c in range(self.MT.total_data_cols()):
6222 self.MT.set_cell_data(r, c, v)
6223
6224 def dropdown_column(
6225 self,
6226 c: Iterator[int] | int | Literal["all"] = 0,
6227 *args,
6228 **kwargs,
6229 ) -> Sheet:
6230 kwargs = get_dropdown_kwargs(*args, **kwargs)
6231 d = get_dropdown_dict(**kwargs)
6232 v = kwargs["set_value"] if kwargs["set_value"] is not None else kwargs["values"][0] if kwargs["values"] else ""
6233 if isinstance(c, str) and c.lower() == "all":
6234 for c_ in range(self.MT.total_data_cols()):
6235 self._dropdown_column(c_, v, d)
6236 elif isinstance(c, int):
6237 self._dropdown_column(c, v, d)
6238 elif is_iterable(c):
6239 for c_ in c:
6240 self._dropdown_column(c_, v, d)
6241 return self.set_refresh_timer(kwargs["redraw"])
6242
6243 def _dropdown_column(self, c: int, v: Any, d: dict) -> None:
6244 self.del_column_options_dropdown_and_checkbox(c)
6245 add_to_options(self.MT.col_options, c, "dropdown", d)
6246 for r in range(self.MT.total_data_rows()):
6247 self.MT.set_cell_data(r, c, v)
6248
6249 def create_header_dropdown(
6250 self,
6251 c: Iterator[int] | int | Literal["all"] = 0,
6252 *args,
6253 **kwargs,
6254 ) -> Sheet:
6255 kwargs = get_dropdown_kwargs(*args, **kwargs)
6256 d = get_dropdown_dict(**kwargs)
6257 v = kwargs["set_value"] if kwargs["set_value"] is not None else kwargs["values"][0] if kwargs["values"] else ""
6258 if isinstance(c, str) and c.lower() == "all":
6259 for c_ in range(self.MT.total_data_cols()):
6260 self._create_header_dropdown(c_, v, d)
6261 elif isinstance(c, int):
6262 self._create_header_dropdown(c, v, d)
6263 elif is_iterable(c):
6264 for c_ in c:
6265 self._create_header_dropdown(c_, v, d)
6266 return self.set_refresh_timer(kwargs["redraw"])
6267
6268 def _create_header_dropdown(self, c: int, v: Any, d: dict) -> None:
6269 self.del_header_cell_options_dropdown_and_checkbox(c)
6270 add_to_options(self.CH.cell_options, c, "dropdown", d)
6271 self.CH.set_cell_data(c, v)
6272
6273 def create_index_dropdown(
6274 self,
6275 r: Iterator[int] | int | Literal["all"] = 0,
6276 *args,
6277 **kwargs,
6278 ) -> Sheet:
6279 kwargs = get_dropdown_kwargs(*args, **kwargs)
6280 d = get_dropdown_dict(**kwargs)
6281 v = kwargs["set_value"] if kwargs["set_value"] is not None else kwargs["values"][0] if kwargs["values"] else ""
6282 if isinstance(r, str) and r.lower() == "all":
6283 for r_ in range(self.MT.total_data_rows()):
6284 self._create_index_dropdown(r_, v, d)
6285 elif isinstance(r, int):
6286 self._create_index_dropdown(r, v, d)
6287 elif is_iterable(r):
6288 for r_ in r:
6289 self._create_index_dropdown(r_, v, d)
6290 return self.set_refresh_timer(kwargs["redraw"])
6291
6292 def _create_index_dropdown(self, r: int, v: Any, d: dict) -> None:
6293 self.del_index_cell_options_dropdown_and_checkbox(r)
6294 add_to_options(self.RI.cell_options, r, "dropdown", d)
6295 self.RI.set_cell_data(r, v)
6296
6297 def delete_dropdown(
6298 self,
6299 r: int | Literal["all"] = 0,
6300 c: int | Literal["all"] = 0,
6301 ) -> None:
6302 if isinstance(r, str) and r.lower() == "all" and isinstance(c, int):
6303 for r_, _ in self.MT.cell_options:
6304 if "dropdown" in self.MT.cell_options[(r_, c)]:
6305 self.del_cell_options_dropdown(r_, c)
6306 elif isinstance(c, str) and c.lower() == "all" and isinstance(r, int):
6307 for _, c_ in self.MT.cell_options:
6308 if "dropdown" in self.MT.cell_options[(r, c_)]:
6309 self.del_cell_options_dropdown(r, c_)
6310 elif isinstance(r, str) and r.lower() == "all" and isinstance(c, str) and c.lower() == "all":
6311 for r_, c_ in self.MT.cell_options:
6312 if "dropdown" in self.MT.cell_options[(r_, c_)]:
6313 self.del_cell_options_dropdown(r_, c_)
6314 elif isinstance(r, int) and isinstance(c, int):
6315 self.del_cell_options_dropdown(r, c)
6316
6317 def delete_cell_dropdown(
6318 self,
6319 r: int | Literal["all"] = 0,
6320 c: int | Literal["all"] = 0,
6321 ) -> None:
6322 self.delete_dropdown(r=r, c=c)
6323
6324 def delete_row_dropdown(
6325 self,
6326 r: Iterator[int] | int | Literal["all"] = "all",
6327 ) -> None:
6328 if isinstance(r, str) and r.lower() == "all":
6329 for r_ in self.MT.row_options:
6330 if "dropdown" in self.MT.row_options[r_]:
6331 self.del_table_row_options_dropdown(r_)
6332 elif isinstance(r, int):
6333 self.del_table_row_options_dropdown(r)
6334 elif is_iterable(r):
6335 for r_ in r:
6336 self.del_table_row_options_dropdown(r_)
6337
6338 def delete_column_dropdown(
6339 self,
6340 c: Iterator[int] | int | Literal["all"] = "all",
6341 ) -> None:
6342 if isinstance(c, str) and c.lower() == "all":
6343 for c_ in self.MT.col_options:
6344 if "dropdown" in self.MT.col_options[c_]:
6345 self.del_column_options_dropdown(datacn=c_)
6346 elif isinstance(c, int):
6347 self.del_column_options_dropdown(datacn=c)
6348 elif is_iterable(c):
6349 for c_ in c:
6350 self.del_column_options_dropdown(datacn=c_)
6351
6352 def delete_header_dropdown(self, c: Iterator[int] | int | Literal["all"]) -> None:
6353 if isinstance(c, str) and c.lower() == "all":
6354 for c_ in self.CH.cell_options:
6355 if "dropdown" in self.CH.cell_options[c_]:
6356 self.del_header_cell_options_dropdown(c_)
6357 elif isinstance(c, int):
6358 self.del_header_cell_options_dropdown(c)
6359 elif is_iterable(c):
6360 for c_ in c:
6361 self.del_header_cell_options_dropdown(c_)
6362
6363 def delete_index_dropdown(self, r: Iterator[int] | int | Literal["all"]) -> None:
6364 if isinstance(r, str) and r.lower() == "all":
6365 for r_ in self.RI.cell_options:
6366 if "dropdown" in self.RI.cell_options[r_]:
6367 self.del_index_cell_options_dropdown(r_)
6368 elif isinstance(r, int):
6369 self.del_index_cell_options_dropdown(r)
6370 elif is_iterable(r):
6371 for r_ in r:
6372 self.del_index_cell_options_dropdown(r_)
6373
6374 def get_dropdowns(self) -> dict:
6375 d = {
6376 **{k: v["dropdown"] for k, v in self.MT.cell_options.items() if "dropdown" in v},
6377 **{k: v["dropdown"] for k, v in self.MT.row_options.items() if "dropdown" in v},
6378 **{k: v["dropdown"] for k, v in self.MT.col_options.items() if "dropdown" in v},
6379 }
6380 if "dropdown" in self.MT.options:
6381 return {**d, "dropdown": self.MT.options["dropdown"]}
6382 return d
6383
6384 def get_header_dropdowns(self) -> dict:
6385 d = {k: v["dropdown"] for k, v in self.CH.cell_options.items() if "dropdown" in v}
6386 if "dropdown" in self.CH.options:
6387 return {**d, "dropdown": self.CH.options["dropdown"]}
6388 return d
6389
6390 def get_index_dropdowns(self) -> dict:
6391 d = {k: v["dropdown"] for k, v in self.RI.cell_options.items() if "dropdown" in v}
6392 if "dropdown" in self.RI.options:
6393 return {**d, "dropdown": self.RI.options["dropdown"]}
6394 return d
6395
6396 def set_dropdown_values(
6397 self,
6398 r: int = 0,
6399 c: int = 0,
6400 set_existing_dropdown: bool = False,
6401 values: list[Any] | None = None,
6402 set_value: Any = None,
6403 ) -> Sheet:
6404 if values is None:
6405 values = []
6406 if set_existing_dropdown:
6407 if self.MT.dropdown.open:
6408 r_, c_ = self.MT.dropdown.get_coords()
6409 else:
6410 raise Exception("No dropdown box is currently open")
6411 else:
6412 r_ = r
6413 c_ = c
6414 kwargs = self.MT.get_cell_kwargs(r, c, key="dropdown")
6415 kwargs["values"] = values
6416 if self.MT.dropdown.open:
6417 self.MT.dropdown.window.values(values)
6418 if set_value is not None:
6419 self.set_cell_data(r_, c_, set_value)
6420 if self.MT.dropdown.open:
6421 self.MT.text_editor.window.set_text(set_value)
6422 return self
6423
6424 def set_header_dropdown_values(
6425 self,
6426 c: int = 0,
6427 set_existing_dropdown: bool = False,
6428 values: list[Any] | None = None,
6429 set_value: Any = None,
6430 ) -> Sheet:
6431 if values is None:
6432 values = []
6433 if set_existing_dropdown:
6434 if self.CH.dropdown.open:
6435 c_ = self.CH.dropdown.get_coords()
6436 else:
6437 raise Exception("No dropdown box is currently open")
6438 else:
6439 c_ = c
6440 kwargs = self.CH.get_cell_kwargs(c_, key="dropdown")
6441 if kwargs:
6442 kwargs["values"] = values
6443 if self.CH.dropdown.open:
6444 self.CH.dropdown.window.values(values)
6445 if set_value is not None:
6446 self.MT.headers(newheaders=set_value, index=c_)
6447
6448 return self
6449
6450 def set_index_dropdown_values(
6451 self,
6452 r: int = 0,
6453 set_existing_dropdown: bool = False,
6454 values: list[Any] | None = None,
6455 set_value: Any = None,
6456 ) -> Sheet:
6457 if values is None:
6458 values = []
6459 if set_existing_dropdown:
6460 if self.RI.current_dropdown_window is not None:
6461 r_ = self.RI.current_dropdown_window.r
6462 else:
6463 raise Exception("No dropdown box is currently open")
6464 else:
6465 r_ = r
6466 kwargs = self.RI.get_cell_kwargs(r_, key="dropdown")
6467 if kwargs:
6468 kwargs["values"] = values
6469 if self.RI.dropdown.open:
6470 self.RI.dropdown.window.values(values)
6471 if set_value is not None:
6472 self.MT.row_index(newindex=set_value, index=r_)
6473 return self
6474
6475 def get_dropdown_values(self, r: int = 0, c: int = 0) -> None | list:
6476 kwargs = self.MT.get_cell_kwargs(r, c, key="dropdown")
6477 if kwargs:
6478 return kwargs["values"]
6479
6480 def get_header_dropdown_values(self, c: int = 0) -> None | list:
6481 kwargs = self.CH.get_cell_kwargs(c, key="dropdown")
6482 if kwargs:
6483 return kwargs["values"]
6484
6485 def get_index_dropdown_values(self, r: int = 0) -> None | list:
6486 kwargs = self.RI.get_cell_kwargs(r, key="dropdown")
6487 if kwargs:
6488 return kwargs["values"]
6489
6490 def dropdown_functions(
6491 self,
6492 r: int,
6493 c: int,
6494 selection_function: Literal[""] | Callable | None = "",
6495 modified_function: Literal[""] | Callable | None = "",
6496 ) -> None | dict:
6497 kwargs = self.MT.get_cell_kwargs(r, c, key="dropdown")
6498 if kwargs:
6499 if selection_function != "":
6500 kwargs["select_function"] = selection_function
6501 if modified_function != "":
6502 kwargs["modified_function"] = modified_function
6503 return kwargs
6504
6505 def header_dropdown_functions(
6506 self,
6507 c: int,
6508 selection_function: Literal[""] | Callable | None = "",
6509 modified_function: Literal[""] | Callable | None = "",
6510 ) -> None | dict:
6511 kwargs = self.CH.get_cell_kwargs(c, key="dropdown")
6512 if selection_function != "":
6513 kwargs["selection_function"] = selection_function
6514 if modified_function != "":
6515 kwargs["modified_function"] = modified_function
6516 return kwargs
6517
6518 def index_dropdown_functions(
6519 self,
6520 r: int,
6521 selection_function: Literal[""] | Callable | None = "",
6522 modified_function: Literal[""] | Callable | None = "",
6523 ) -> None | dict:
6524 kwargs = self.RI.get_cell_kwargs(r, key="dropdown")
6525 if selection_function != "":
6526 kwargs["select_function"] = selection_function
6527 if modified_function != "":
6528 kwargs["modified_function"] = modified_function
6529 return kwargs
6530
6531 def get_dropdown_value(self, r: int = 0, c: int = 0) -> Any:
6532 if self.MT.get_cell_kwargs(r, c, key="dropdown"):
6533 return self.get_cell_data(r, c)
6534
6535 def get_header_dropdown_value(self, c: int = 0) -> Any:
6536 if self.CH.get_cell_kwargs(c, key="dropdown"):
6537 return self.MT._headers[c]
6538
6539 def get_index_dropdown_value(self, r: int = 0) -> Any:
6540 if self.RI.get_cell_kwargs(r, key="dropdown"):
6541 return self.MT._row_index[r]
6542
6543 def format_cell(
6544 self,
6545 r: int | Literal["all"],
6546 c: int | Literal["all"],
6547 formatter_options: dict | None = None,
6548 formatter_class: Any = None,
6549 redraw: bool = True,
6550 **kwargs,
6551 ) -> Sheet:
6552 if formatter_options is None:
6553 formatter_options = {}
6554 kwargs = fix_format_kwargs({"formatter": formatter_class, **formatter_options, **kwargs})
6555 if isinstance(r, str) and r.lower() == "all" and isinstance(c, int):
6556 for r_ in range(self.MT.total_data_rows()):
6557 self._format_cell(r_, c, kwargs)
6558 elif isinstance(c, str) and c.lower() == "all" and isinstance(r, int):
6559 for c_ in range(self.MT.total_data_cols()):
6560 self._format_cell(r, c_, kwargs)
6561 elif isinstance(r, str) and r.lower() == "all" and isinstance(c, str) and c.lower() == "all":
6562 for r_ in range(self.MT.total_data_rows()):
6563 for c_ in range(self.MT.total_data_cols()):
6564 self._format_cell(r_, c_, kwargs)
6565 else:
6566 self._format_cell(r, c, kwargs)
6567 return self.set_refresh_timer(redraw)
6568
6569 def _format_cell(self, r: int, c: int, d: dict) -> None:
6570 v = d["value"] if "value" in d else self.MT.get_cell_data(r, c)
6571 self.del_cell_options_checkbox(r, c)
6572 add_to_options(self.MT.cell_options, (r, c), "format", d)
6573 self.MT.set_cell_data(r, c, value=v, kwargs=d)
6574
6575 def delete_cell_format(
6576 self,
6577 r: Literal["all"] | int = "all",
6578 c: Literal["all"] | int = "all",
6579 clear_values: bool = False,
6580 ) -> Sheet:
6581 if isinstance(r, str) and r.lower() == "all" and isinstance(c, int):
6582 for r_, _ in self.MT.cell_options:
6583 if "format" in self.MT.cell_options[(r_, c)]:
6584 self.MT.delete_cell_format(r_, c, clear_values=clear_values)
6585 elif isinstance(c, str) and c.lower() == "all" and isinstance(r, int):
6586 for _, c_ in self.MT.cell_options:
6587 if "format" in self.MT.cell_options[(r, c_)]:
6588 self.MT.delete_cell_format(r, c_, clear_values=clear_values)
6589 elif isinstance(r, str) and r.lower() == "all" and isinstance(c, str) and c.lower() == "all":
6590 for r_, c_ in self.MT.cell_options:
6591 if "format" in self.MT.cell_options[(r_, c_)]:
6592 self.MT.delete_cell_format(r_, c_, clear_values=clear_values)
6593 else:
6594 self.MT.delete_cell_format(r, c, clear_values=clear_values)
6595 return self
6596
6597 def format_row(
6598 self,
6599 r: Iterator[int] | int | Literal["all"],
6600 formatter_options: dict | None = None,
6601 formatter_class: Any = None,
6602 redraw: bool = True,
6603 **kwargs,
6604 ) -> Sheet:
6605 if formatter_options is None:
6606 formatter_options = {}
6607 kwargs = fix_format_kwargs({"formatter": formatter_class, **formatter_options, **kwargs})
6608 if isinstance(r, str) and r.lower() == "all":
6609 for r_ in range(len(self.MT.data)):
6610 self._format_row(r_, kwargs)
6611 elif is_iterable(r):
6612 for r_ in r:
6613 self._format_row(r_, kwargs)
6614 else:
6615 self._format_row(r, kwargs)
6616 return self.set_refresh_timer(redraw)
6617
6618 def _format_row(self, r: int, d: dict) -> None:
6619 self.del_row_options_checkbox(r)
6620 add_to_options(self.MT.row_options, r, "format", d)
6621 for c in range(self.MT.total_data_cols()):
6622 self.MT.set_cell_data(
6623 r,
6624 c,
6625 value=d["value"] if "value" in d else self.MT.get_cell_data(r, c),
6626 kwargs=d,
6627 )
6628
6629 def delete_row_format(
6630 self,
6631 r: Iterator[int] | int | Literal["all"] = "all",
6632 clear_values: bool = False,
6633 ) -> Sheet:
6634 if is_iterable(r):
6635 for r_ in r:
6636 self.MT.delete_row_format(r_, clear_values=clear_values)
6637 else:
6638 self.MT.delete_row_format(r, clear_values=clear_values)
6639 return self
6640
6641 def format_column(
6642 self,
6643 c: Iterator[int] | int | Literal["all"],
6644 formatter_options: dict | None = None,
6645 formatter_class: Any = None,
6646 redraw: bool = True,
6647 **kwargs,
6648 ) -> Sheet:
6649 if formatter_options is None:
6650 formatter_options = {}
6651 kwargs = fix_format_kwargs({"formatter": formatter_class, **formatter_options, **kwargs})
6652 if isinstance(c, str) and c.lower() == "all":
6653 for c_ in range(self.MT.total_data_cols()):
6654 self._format_column(c_, kwargs)
6655 elif is_iterable(c):
6656 for c_ in c:
6657 self._format_column(c_, kwargs)
6658 else:
6659 self._format_column(c, kwargs)
6660 return self.set_refresh_timer(redraw)
6661
6662 def _format_column(self, c: int, d: dict) -> None:
6663 self.del_column_options_checkbox(c)
6664 add_to_options(self.MT.col_options, c, "format", d)
6665 for r in range(self.MT.total_data_rows()):
6666 self.MT.set_cell_data(
6667 r,
6668 c,
6669 value=d["value"] if "value" in d else self.MT.get_cell_data(r, c),
6670 kwargs=d,
6671 )
6672
6673 def delete_column_format(
6674 self,
6675 c: Iterator[int] | int | Literal["all"] = "all",
6676 clear_values: bool = False,
6677 ) -> Sheet:
6678 if is_iterable(c):
6679 for c_ in c:
6680 self.MT.delete_column_format(c_, clear_values=clear_values)
6681 else:
6682 self.MT.delete_column_format(c, clear_values=clear_values)
6683 return self
6684
6685
6686 class Dropdown(Sheet):
6687 def __init__(
6688 self,
6689 parent: tk.Misc,
6690 r: int,
6691 c: int,
6692 bg: str,
6693 fg: str,
6694 select_bg: str,
6695 select_fg: str,
6696 ops: dict,
6697 outline_color: str,
6698 width: int | None = None,
6699 height: int | None = None,
6700 font: None | tuple[str, int, str] = None,
6701 outline_thickness: int = 2,
6702 values: list[Any] | None = None,
6703 close_dropdown_window: Callable | None = None,
6704 search_function: Callable = dropdown_search_function,
6705 modified_function: None | Callable = None,
6706 arrowkey_RIGHT: Callable | None = None,
6707 arrowkey_LEFT: Callable | None = None,
6708 align: str = "nw",
6709 # False for using r, c
6710 # "r" for r
6711 # "c" for c
6712 single_index: Literal["r", "c"] | bool = False,
6713 ) -> None:
6714 Sheet.__init__(
6715 self,
6716 parent=parent,
6717 name="!SheetDropdown",
6718 outline_thickness=outline_thickness,
6719 show_horizontal_grid=True,
6720 show_vertical_grid=False,
6721 show_header=False,
6722 show_row_index=False,
6723 show_top_left=False,
6724 empty_horizontal=0,
6725 empty_vertical=0,
6726 selected_rows_to_end_of_window=True,
6727 horizontal_grid_to_end_of_window=True,
6728 set_cell_sizes_on_zoom=True,
6729 show_selected_cells_border=False,
6730 scrollbar_show_arrows=False,
6731 )
6732 self.parent = parent
6733 self.close_dropdown_window = close_dropdown_window
6734 self.arrowkey_RIGHT = arrowkey_RIGHT
6735 self.arrowkey_LEFT = arrowkey_LEFT
6736 self.single_index = single_index
6737 self.bind("<Motion>", self.mouse_motion)
6738 self.bind("<ButtonPress-1>", self.b1)
6739 self.bind("<Up>", self.arrowkey_UP)
6740 self.bind("<Tab>", self.arrowkey_RIGHT)
6741 self.bind("<Right>", self.arrowkey_RIGHT)
6742 self.bind("<Down>", self.arrowkey_DOWN)
6743 self.bind("<Left>", self.arrowkey_LEFT)
6744 self.bind("<Prior>", self.arrowkey_UP)
6745 self.bind("<Next>", self.arrowkey_DOWN)
6746 self.bind("<Return>", self.b1)
6747 self.reset(
6748 r=r,
6749 c=c,
6750 bg=bg,
6751 fg=fg,
6752 select_bg=select_bg,
6753 select_fg=select_fg,
6754 width=width,
6755 height=height,
6756 font=font,
6757 ops=ops,
6758 outline_color=outline_color,
6759 align=align,
6760 values=[] if values is None else values,
6761 search_function=search_function,
6762 modified_function=modified_function,
6763 )
6764
6765 def reset(
6766 self,
6767 r: int,
6768 c: int,
6769 bg: str,
6770 fg: str,
6771 select_bg: str,
6772 select_fg: str,
6773 width: int,
6774 height: int,
6775 font: tuple[str, int, str],
6776 ops: DotDict,
6777 outline_color: str,
6778 align: str,
6779 values: list[Any] | None = None,
6780 search_function: Callable = dropdown_search_function,
6781 modified_function: None | Callable = None,
6782 ) -> None:
6783 self.set_yview(0.0)
6784 self.deselect(redraw=False)
6785 self.r = r
6786 self.c = c
6787 self.row = -1
6788 self.search_function = search_function
6789 self.modified_function = modified_function
6790 self.height_and_width(height=height, width=width)
6791 self.table_align(align)
6792 self.set_options(
6793 outline_color=outline_color,
6794 table_grid_fg=fg,
6795 table_selected_cells_border_fg=fg,
6796 table_selected_cells_bg=select_bg,
6797 table_selected_rows_border_fg=fg,
6798 table_selected_rows_bg=select_bg,
6799 table_selected_rows_fg=select_fg,
6800 table_selected_box_cells_fg=select_bg,
6801 table_selected_box_rows_fg=select_bg,
6802 font=font,
6803 table_fg=fg,
6804 table_bg=bg,
6805 **{k: ops[k] for k in scrollbar_options_keys},
6806 )
6807 self.values(values, width=width - self.yscroll.winfo_width() - 4)
6808
6809 def arrowkey_UP(self, event: Any = None) -> None:
6810 if self.row > 0:
6811 self.row -= 1
6812 else:
6813 self.row = 0
6814 self.see(self.row, 0, redraw=False)
6815 self.select_row(self.row)
6816
6817 def arrowkey_DOWN(self, event: Any = None) -> None:
6818 if len(self.MT.data) - 1 > self.row:
6819 self.row += 1
6820 self.see(self.row, 0, redraw=False)
6821 self.select_row(self.row)
6822
6823 def search_and_see(self, event: Any = None) -> str:
6824 if self.search_function is not None:
6825 rn = self.search_function(search_for=rf"{event['value']}", data=(r[0] for r in self.MT.data))
6826 if isinstance(rn, int):
6827 self.row = rn
6828 self.see(self.row, 0, redraw=False)
6829 self.select_row(self.row)
6830 return self.MT.data[rn][0]
6831
6832 def mouse_motion(self, event: Any) -> None:
6833 row = self.identify_row(event, exclude_index=True, allow_end=False)
6834 if row is not None and row != self.row:
6835 self.row = row
6836 self.select_row(self.row)
6837
6838 def _reselect(self) -> None:
6839 rows = self.get_selected_rows()
6840 if rows:
6841 self.select_row(next(iter(rows)))
6842
6843 def b1(self, event: Any = None) -> None:
6844 if event is None:
6845 row = None
6846 elif event.keysym == "Return":
6847 row = self.get_selected_rows()
6848 row = None if not row else next(iter(row))
6849 else:
6850 row = self.identify_row(event, exclude_index=True, allow_end=False)
6851 if self.single_index:
6852 if row is None:
6853 self.close_dropdown_window(self.r if self.single_index == "r" else self.c)
6854 else:
6855 self.close_dropdown_window(
6856 self.r if self.single_index == "r" else self.c,
6857 self.get_cell_data(row, 0),
6858 )
6859 else:
6860 if row is None:
6861 self.close_dropdown_window(self.r, self.c)
6862 else:
6863 self.close_dropdown_window(self.r, self.c, self.get_cell_data(row, 0))
6864
6865 def get_coords(self) -> int | tuple[int, int]:
6866 if self.single_index == "r":
6867 return self.r
6868 elif self.single_index == "c":
6869 return self.c
6870 return self.r, self.c
6871
6872 def values(
6873 self,
6874 values: list[Any] | None = None,
6875 redraw: bool = True,
6876 width: int | None = None,
6877 ) -> None:
6878 if values is None:
6879 values = []
6880 self.set_sheet_data(
6881 [[v] for v in values],
6882 reset_col_positions=False,
6883 reset_row_positions=False,
6884 redraw=False,
6885 verify=False,
6886 )
6887 self.set_all_cell_sizes_to_text(redraw=redraw, width=width, slim=True)