### Get Example Column Widths Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Retrieves a list of default column width values for a specified total number of columns. Useful for initializing sheet dimensions. ```python get_example_canvas_column_widths(total_cols: int | None = None) -> list[float] ``` -------------------------------- ### Get Example Row Heights Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Retrieves a list of default row height values for a specified total number of rows. Useful for initializing sheet dimensions. ```python get_example_canvas_row_heights(total_rows: int | None = None) -> list[float] ``` -------------------------------- ### Install tksheet using Pip Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Installs or upgrades the tksheet library using pip. Ensure you have Python and pip installed. ```bash #To install using pip pip install tksheet #To update using pip pip install tksheet --upgrade ``` -------------------------------- ### Install tksheet from Source Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Installs tksheet from its source code using pip. This method requires downloading the source and navigating to the directory containing 'pyproject.toml'. ```bash pip install -e . ``` -------------------------------- ### Get Column Options Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Get internal storage dictionary of highlights, readonly columns, dropdowns etc. Specifically for column options. ```APIDOC ## GET /column/options ### Description Get internal storage dictionary of highlights, readonly columns, dropdowns etc. Specifically for column options. ### Method GET ### Endpoint /column/options ### Parameters #### Query Parameters - **key** (str, optional) - The specific option key to retrieve. ### Response #### Success Response (200) - **dict** - A dictionary containing the column options. #### Response Example ```json { "readonly": { "2": true } } ``` ``` -------------------------------- ### Get Index Options Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Get internal storage dictionary of highlights, readonly row index cells, dropdowns etc. Specifically for row index options. ```APIDOC ## GET /index/options ### Description Get internal storage dictionary of highlights, readonly row index cells, dropdowns etc. Specifically for row index options. ### Method GET ### Endpoint /index/options ### Parameters #### Query Parameters - **key** (str, optional) - The specific option key to retrieve. ### Response #### Success Response (200) - **dict** - A dictionary containing the index options. #### Response Example ```json { "checkbox": { "0": true } } ``` ``` -------------------------------- ### Get Header Options Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Get internal storage dictionary of highlights, readonly header cells, dropdowns etc. Specifically for header options. ```APIDOC ## GET /header/options ### Description Get internal storage dictionary of highlights, readonly header cells, dropdowns etc. Specifically for header options. ### Method GET ### Endpoint /header/options ### Parameters #### Query Parameters - **key** (str, optional) - The specific option key to retrieve. ### Response #### Success Response (200) - **dict** - A dictionary containing the header options. #### Response Example ```json { "format": { "A": "currency" } } ``` ``` -------------------------------- ### Get Row Options Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Get internal storage dictionary of highlights, readonly rows, dropdowns etc. Specifically for row options. ```APIDOC ## GET /row/options ### Description Get internal storage dictionary of highlights, readonly rows, dropdowns etc. Specifically for row options. ### Method GET ### Endpoint /row/options ### Parameters #### Query Parameters - **key** (str, optional) - The specific option key to retrieve. ### Response #### Success Response (200) - **dict** - A dictionary containing the row options. #### Response Example ```json { "highlight": { "1": "#FFFF00" } } ``` ``` -------------------------------- ### Get Cell Options Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Get internal storage dictionary of highlights, readonly cells, dropdowns etc. Specifically for cell options. ```APIDOC ## GET /cell/options ### Description Get internal storage dictionary of highlights, readonly cells, dropdowns etc. Specifically for cell options. ### Method GET ### Endpoint /cell/options ### Parameters #### Query Parameters - **key** (str, optional) - The specific option key to retrieve. - **canvas** (str, optional) - The canvas to retrieve options from ('table', 'row_index', 'header'). Defaults to 'table'. ### Response #### Success Response (200) - **dict** - A dictionary containing the cell options. #### Response Example ```json { "readonly": { "0,0": true } } ``` ``` -------------------------------- ### Get All Column Text Alignments Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Retrieves a dictionary of all currently set text alignment rules for columns. ```python get_column_alignments() -> dict ``` -------------------------------- ### Get All Selection Boxes Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Retrieves all defined selection boxes, returning their coordinates. ```APIDOC ## GET /selection/boxes ### Description Retrieves all defined selection boxes and returns their coordinates as a tuple of tuples. Each inner tuple represents a selection box in the format (min_row, min_col, max_row, max_col). ### Method GET ### Endpoint /selection/boxes ### Response #### Success Response (200) - **selection_boxes** (tuple[tuple[int, int, int, int]]) - A tuple containing tuples, where each inner tuple represents a selection box (min_row, min_col, max_row, max_col). #### Response Example ```json { "selection_boxes": [ [0, 0, 5, 5], [10, 10, 12, 12] ] } ``` ``` -------------------------------- ### Get All Row Text Alignments Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Retrieves a dictionary of all currently set text alignment rules for rows. ```python get_row_alignments() -> dict ``` -------------------------------- ### Get All Column Options (Python) Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Retrieves the internal storage dictionary for column options, such as highlights, readonly settings, and dropdowns. Filtering by a specific key is supported. ```python get_column_options(key: None | str = None) -> dict ``` -------------------------------- ### Get Ctrl+X/Ctrl+C Boxes Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Retrieves selection boxes relevant for Ctrl+X/Ctrl+C operations, with an option to include row counts. ```APIDOC ## GET /selection/ctrl_x_c_boxes ### Description Retrieves selection boxes that are typically used for copy-paste operations (Ctrl+X, Ctrl+C). It can optionally return the number of rows included in these selections. ### Method GET ### Endpoint /selection/ctrl_x_c_boxes ### Query Parameters - **nrows** (bool) - Optional - If True, the response will include the count of rows in the selections. ### Response #### Success Response (200) - **selection_data** (dict[tuple[int, int, int, int], str]) - A dictionary where keys are selection box tuples (min_row, min_col, max_row, max_col) and values are their types. - **row_count** (int) - Optional - The total number of rows covered by the selections, if `nrows` is True. #### Response Example ```json { "selection_data": { "(0, 0, 5, 5)": "cell" }, "row_count": 6 } ``` ``` -------------------------------- ### Get All Row Options (Python) Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Retrieves the internal storage dictionary for row options, including highlights, readonly settings, and dropdowns. It can be filtered by a specific key. ```python get_row_options(key: None | str = None) -> dict ``` -------------------------------- ### Get Visible Columns Property Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index A property that returns a tuple representing the start and end column indices of the currently visible columns in the sheet. Example usage: `start_column, end_column = sheet.visible_columns`. ```python @property visible_columns() -> tuple[int, int] ``` -------------------------------- ### Get Visible Rows Property Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index A property that returns a tuple representing the start and end row indices of the currently visible rows in the sheet. Example usage: `start_row, end_row = sheet.visible_rows`. ```python @property visible_rows() -> tuple[int, int] ``` -------------------------------- ### Apply Float Formatting to Columns using tksheet Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index This example demonstrates how to use the `float_formatter` in `tksheet` to format columns as floating-point numbers. It shows how to apply formatting with specific decimal places and nullability options, both within the formatter and as direct keyword arguments to the `sheet.format` method. ```python import tkinter as tk from tksheet import ( Sheet, float_formatter, ) from tksheet import ( num2alpha, ) class demo(tk.Tk): def __init__(self): super().__init__() self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self.sheet = Sheet( self, data=[[f"{r}", f"{r}"] for r in range(5)], expand_sheet_if_paste_too_big=True, theme="dark blue", ) """ Format example """ # some keyword arguments inside float_formatter() self.sheet.format( num2alpha(0), # column A formatter_options=float_formatter( decimals=1, nullable=True, ), ) # some keyword arguments outside # of float_formatter() instead self.sheet.format( "B", # column B formatter_options=float_formatter(), decimals=3, nullable=False, ) """ Rest of code """ self.sheet.grid(row=0, column=0, sticky="nswe") self.sheet.enable_bindings( "all", "ctrl_select", "edit_header", "edit_index", ) app = demo() app.mainloop() ``` -------------------------------- ### Data Formatting Overview Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index An introduction to data formatting in tksheet, explaining its purpose in handling different data types, enforcing strict typing, and providing custom display logic. ```APIDOC # Data Formatting ### Description Data formatting in tksheet allows for the conversion of sheet data and user input to specific data types, providing greater functionality and strict typing. It also enables custom display logic for data in the table GUI and handles invalid or missing data. ### Key Features - **Type Conversion**: Convert sheet data and user input to designated data types. - **Strict Typing**: Enforce specific data types for cells. - **Custom Display**: Define how data is presented in the table GUI (e.g., rounded floats). - **Error Handling**: Logic for managing invalid and missing data. - **Built-in and Custom Formatters**: tksheet offers pre-defined formatters and supports the creation of custom ones. ### Further Information - **Formatter Options**: Refer to [documentation link] for details on `formatter_options` arguments. - **Demonstration**: See [documentation link] for examples of built-in and custom formatters. ``` -------------------------------- ### Get Readonly Table Data Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index This property provides read-only access to the sheet's internal data. It excludes header and index data. Example usage is `self.sheet.data`. ```python @property data() # Example: self.sheet.data # Doesn't include header or index data. ``` -------------------------------- ### Create and Configure tksheet for Readme Screenshot (Python) Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index This Python code demonstrates the creation of a tksheet widget within a Tkinter application. It initializes the sheet with data, headers, and various visual configurations like themes, alignment, and dimensions. It also includes methods for enabling bindings and adding custom commands to the popup menu. ```python from tksheet import ( Sheet, num2alpha as n2a, ) import tkinter as tk class demo(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self.frame = tk.Frame(self) self.frame.grid_columnconfigure(0, weight=1) self.frame.grid_rowconfigure(0, weight=1) self.sheet = Sheet( self.frame, empty_horizontal=0, empty_vertical=0, paste_can_expand_x=True, paste_can_expand_y=True, align="w", header_align="c", data=[[f"Row {r}, Column {c}\nnewline 1\nnewline 2" for c in range(6)] for r in range(21)], headers=[ "Dropdown Column", "Checkbox Column", "Center Aligned Column", "East Aligned Column", "", "", ], theme="dark", height=520, width=930, ) self.sheet.enable_bindings("all", "edit_index", "edit_header") self.sheet.popup_menu_add_command( "Hide Rows", self.hide_rows, table_menu=False, header_menu=False, empty_space_menu=False, ) self.sheet.popup_menu_add_command( "Show All Rows", self.show_rows, table_menu=False, header_menu=False, empty_space_menu=False, ) self.sheet.popup_menu_add_command( "Hide Columns", self.hide_columns, table_menu=False, index_menu=False, empty_space_menu=False, ) self.sheet.popup_menu_add_command( "Show All Columns", self.show_columns, table_menu=False, index_menu=False, empty_space_menu=False, ) self.frame.grid(row=0, column=0, sticky="nswe") self.sheet.grid(row=0, column=0, sticky="nswe") colors = ( "#509f56", "#64a85b", "#78b160", "#8cba66", "#a0c36c", "#b4cc71", "#c8d576", "#dcde7c", "#f0e782", "#ffec87", "#ffe182", "#ffdc7d", "#ffd77b", "#ffc873", "#ffb469", "#fea05f", "#fc8c55", "#fb784b", "#fa6441", "#f85037", ) self.sheet.align_columns(columns=2, align="c") self.sheet.align_columns(columns=3, align="e") self.sheet.create_index_dropdown(r=0, values=["Dropdown"] + [f"{i}" for i in range(15)]) self.sheet.create_index_checkbox(r=3, checked=True, text="Checkbox") self.sheet.create_dropdown(r="all", c=0, values=["Dropdown"] + [f"{i}" for i in range(15)]) self.sheet.create_checkbox(r="all", c=1, checked=True, text="Checkbox") self.sheet.create_header_dropdown(c=0, values=["Header Dropdown"] + [f"{i}" for i in range(15)]) self.sheet.create_header_checkbox(c=1, checked=True, text="Header Checkbox") self.sheet.align_cells(5, 0, align="c") self.sheet.highlight_cells(5, 0, bg="gray50", fg="blue") self.sheet.highlight_cells(17, canvas="index", bg="yellow", fg="black") self.sheet.highlight_cells(12, 1, bg="gray90", fg="purple") for r in range(len(colors)): self.sheet.highlight_cells(row=r, column=3, fg=colors[r]) self.sheet.highlight_cells(row=r, column=4, bg=colors[r], fg="black") self.sheet.highlight_cells(row=r, column=5, bg=colors[r], fg="purple") self.sheet.highlight_cells(column=5, canvas="header", bg="white", fg="purple") self.sheet.align(n2a(2), align="c") self.sheet.align(n2a(3), align="e") self.sheet.dropdown( self.sheet.span("A", header=True), values=["Dropdown"] + [f"{i}" for i in range(15)], ) self.sheet.checkbox( self.sheet.span("B", header=True), checked=True, text="Checkbox", ) self.sheet.align(5, 0, align="c") self.sheet.highlight(5, 0, bg="gray50", fg="blue") self.sheet.highlight( self.sheet.span(17, index=True, table=False), bg="yellow", fg="black", ) self.sheet.highlight(12, 1, bg="gray90", fg="purple") for r in range(len(colors)): self.sheet.highlight(r, 3, fg=colors[r]) self.sheet.highlight(r, 4, bg=colors[r], fg="black") self.sheet.highlight(r, 5, bg=colors[r], fg="purple") self.sheet.highlight( self.sheet.span(n2a(5), header=True, table=False), bg="white", fg="purple", ) ``` -------------------------------- ### Get Span Kind Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Retrieves the type of a span, which can be 'cell', 'row', or 'column'. This property is useful for understanding the scope of the span. The examples demonstrate how different span definitions result in different kinds. ```python span = sheet.span("A1:C4") print (span.kind) # prints "cell" span = sheet.span(":") print (span.kind) # prints "cell" span = sheet.span("1:3") print (span.kind) # prints "row" span = sheet.span("A:C") print (span.kind) # prints "column" # after importing num2alpha from tksheet print (sheet[num2alpha(0)].kind) # prints "column" ``` -------------------------------- ### Creating a Treeview Mode Sheet Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Demonstrates how to initialize a Tksheet instance in treeview mode or convert an existing sheet to treeview mode. ```APIDOC ## Creating a Treeview Mode Sheet You can make a treeview mode sheet by using the initialization parameter `treeview`: ```python sheet = Sheet(parent, treeview=True) ``` Or by using `Sheet.reset()` and `Sheet.set_options()`: ```python my_sheet.reset() my_sheet.set_options(treeview=True) ``` See the other sections on sheet initialization and examples for the other usual `Sheet()` parameters. ``` -------------------------------- ### Get vertical scroll view (Python) Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Retrieves the current vertical scroll view of the Sheet as a tuple of two floats representing the start and end positions. This is useful for understanding the current scroll state. ```python get_yview() -> tuple[float, float] ``` -------------------------------- ### Get horizontal scroll view (Python) Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Retrieves the current horizontal scroll view of the Sheet as a tuple of two floats representing the start and end positions. This is useful for understanding the current scroll state. ```python get_xview() -> tuple[float, float] ``` -------------------------------- ### Get Span Rows and Columns Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Accesses the row and column ranges of a span using the `.rows` and `.columns` properties. These return a `SpanRange` object that can be iterated over, checked for membership, compared for equality, and its length can be determined. The examples primarily show usage with `.rows`, but `.columns` functions identically. ```python # use as an iterator span = sheet.span("A1:C4") for row in span.rows: pass # use as a reversed iterator for row in reversed(span.rows): pass # check row membership span = sheet.span("A1:C4") print (2 in span.rows) # prints True # check span.rows equality, also can do not equal span = self.sheet["A1:C4"] span2 = self.sheet["1:4"] print (span.rows == span2.rows) # prints True # check len span = self.sheet["A1:C4"] print (len(span.rows)) # prints 4 ``` -------------------------------- ### Tkinter Application with tksheet Widget Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index A complete example of a tkinter application that integrates a tksheet widget. It configures grid weights for resizing and populates the sheet with sample data. ```python from tksheet import Sheet import tkinter as tk class demo(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.grid_columnconfigure(0, weight = 1) self.grid_rowconfigure(0, weight = 1) self.frame = tk.Frame(self) self.frame.grid_columnconfigure(0, weight = 1) self.frame.grid_rowconfigure(0, weight = 1) self.sheet = Sheet(self.frame, data = [[f"Row {r}, Column {c}\nnewline1\nnewline2" for c in range(50)] for r in range(500)]) self.sheet.enable_bindings() self.frame.grid(row = 0, column = 0, sticky = "nswe") self.sheet.grid(row = 0, column = 0, sticky = "nswe") app = demo() app.mainloop() ``` -------------------------------- ### tksheet Initialization Options Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Defines the `__init__` method for the tksheet widget, specifying all possible initialization parameters and their default values. This includes options for controlling the display of various elements, setting dimensions, handling data, configuring fonts, managing undo history, and customizing appearance. ```python def __init__( parent: tk.Misc, name: str = "!sheet", show_table: bool = True, show_top_left: bool | None = None, show_row_index: bool = True, show_header: bool = True, show_x_scrollbar: bool = True, show_y_scrollbar: bool = True, width: int | None = None, height: int | None = None, headers: None | list[Any] = None, header: None | list[Any] = None, row_index: None | list[Any] = None, index: None | list[Any] = None, default_header: Literal["letters", "numbers", "both"] | None = "letters", default_row_index: Literal["letters", "numbers", "both"] | None = "numbers", data_reference: None | Sequence[Sequence[Any]] = None, data: None | Sequence[Sequence[Any]] = None, # either (start row, end row, "rows"), (start column, end column, "rows") or # (cells start row, cells start column, cells end row, cells end column, "cells") # noqa: E501 startup_select: tuple[int, int, str] | tuple[int, int, int, int, str] = None, startup_focus: bool = True, total_columns: int | None = None, total_rows: int | None = None, default_column_width: int = 120, default_header_height: str | int = "1", default_row_index_width: int = 70, default_row_height: str | int = "1", min_column_width: int = 1, max_column_width: float = float("inf"), max_row_height: float = float("inf"), max_header_height: float = float("inf"), max_index_width: float = float("inf"), after_redraw_time_ms: int = 16, set_all_heights_and_widths: bool = False, zoom: int = 100, align: str = "nw", header_align: str = "n", row_index_align: str | None = None, index_align: str = "n", displayed_columns: list[int] | None = None, all_columns_displayed: bool = True, displayed_rows: list[int] | None = None, all_rows_displayed: bool = True, to_clipboard_dialect: csv.Dialect = csv.excel_tab, to_clipboard_delimiter: str = "\t", to_clipboard_quotechar: str = '"', to_clipboard_lineterminator: str = "\n", from_clipboard_delimiters: list[str] | str = "\t", show_default_header_for_empty: bool = True, show_default_index_for_empty: bool = True, page_up_down_select_row: bool = True, paste_can_expand_x: bool = False, paste_can_expand_y: bool = False, paste_insert_column_limit: int | None = None, paste_insert_row_limit: int | None = None, show_dropdown_borders: bool = False, arrow_key_down_right_scroll_page: bool = False, cell_auto_resize_enabled: bool = True, auto_resize_row_index: bool | Literal["empty"] = "empty", auto_resize_columns: int | None = None, auto_resize_rows: int | None = None, set_cell_sizes_on_zoom: bool = False, font: tuple[str, int, str] = FontTuple( "Calibri", 13 if USER_OS == "darwin" else 11, "normal", ), header_font: tuple[str, int, str] = FontTuple( "Calibri", 13 if USER_OS == "darwin" else 11, "normal", ), index_font: tuple[str, int, str] = FontTuple( "Calibri", 13 if USER_OS == "darwin" else 11, "normal", ), # currently has no effect popup_menu_font: tuple[str, int, str] = FontTuple( "Calibri", 13 if USER_OS == "darwin" else 11, "normal", ), max_undos: int = 30, column_drag_and_drop_perform: bool = True, row_drag_and_drop_perform: bool = True, empty_horizontal: int = 50, empty_vertical: int = 50, selected_rows_to_end_of_window: bool = False, horizontal_grid_to_end_of_window: bool = False, vertical_grid_to_end_of_window: bool = False, show_vertical_grid: bool = True, show_horizontal_grid: bool = True, display_selected_fg_over_highlights: bool = False, show_selected_cells_border: bool = True, edit_cell_tab: Literal["right", "down", ""] = "right", edit_cell_return: Literal["right", "down", ""] = "down", editor_del_key: Literal["forward", "backward", ""] = "forward", treeview: bool = False, treeview_indent: str | int = "2", rounded_boxes: bool = True, alternate_color: str = "", allow_cell_overflow: bool = False, # "" no wrap, "w" word wrap, "c" char wrap table_wrap: Literal["", "w", "c"] = "c", index_wrap: Literal["", "w", "c"] = "c", header_wrap: Literal["", "w", "c"] = "c", sort_key: Callable = natural_sort_key, tooltips: bool = False, user_can_create_notes: bool = False, note_corners: bool = False, tooltip_width: int = 210, tooltip_height: int = 210, tooltip_hover_delay: int = 1200, # colors outline_thickness: int = 0, theme: str = "light blue", outline_color: str = theme_light_blue["outline_color"], frame_bg: str = theme_light_blue["table_bg"], ): pass ``` -------------------------------- ### Expand Span and Customize Data Retrieval Options Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Illustrates how to expand a span to cover a larger area and use the `.options()` method to customize data retrieval. Options include specifying whether to include the table, header, and index, as well as display settings. ```python "entire sheet including headers and index" entire_sheet_data = self.sheet["A1"].expand().options(header=True, index=True).data "header data, no table or index data" # a list of displayed header cells header_data = self.sheet["A:C"].options(table=False, header=True).data # a header value header_data = self.sheet["A"].options(table=False, hdisp=False, header=True).data "index data, no table or header data" # a list of displayed index cells index_data = self.sheet[:3].options(table=False, index=True).data # or using sheet.span() a list of displayed index cells index_data = self.sheet.span(slice(None, 3), table=False, index=True).data # a row index value index_data = self.sheet[3].options(table=False, idisp=False, index=True).data ``` -------------------------------- ### Get Selected Cells Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Get the coordinates of the currently selected cells. Returns displayed coordinates. ```APIDOC ## GET /selected/cells ### Description Get the coordinates of the currently selected cells. Returns displayed coordinates. ### Method GET ### Endpoint /selected/cells ### Parameters #### Query Parameters - **get_rows** (bool, optional) - Whether to get rows. - **get_columns** (bool, optional) - Whether to get columns. - **sort_by_row** (bool, optional) - Whether to sort by row. - **sort_by_column** (bool, optional) - Whether to sort by column. - **reverse** (bool, optional) - Whether to reverse the sort order. ### Response #### Success Response (200) - **list[tuple[int, int]] | set[tuple[int, int]]** - A list or set of selected cell coordinates (row, column). #### Response Example ```json [[1, 2], [3, 4], [5, 6]] ``` ``` -------------------------------- ### Get Selected Columns Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Get the indices of the currently selected columns. Returns displayed indices. ```APIDOC ## GET /selected/columns ### Description Get the indices of the currently selected columns. Returns displayed indices. ### Method GET ### Endpoint /selected/columns ### Parameters #### Query Parameters - **get_cells** (bool, optional) - Whether to get cells as columns. - **get_cells_as_columns** (bool, optional) - Whether to get cells as columns. - **return_tuple** (bool, optional) - Whether to return the result as a tuple. ### Response #### Success Response (200) - **tuple[int] | tuple[tuple[int, int]] | set[int] | set[tuple[int, int]]** - A collection of selected column indices or cell coordinates. #### Response Example ```json [0, 2, 4] ``` ``` -------------------------------- ### Create List Box Widget with tksheet Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Demonstrates how to create a custom list box widget by subclassing the tksheet.Sheet class. This example customizes the appearance to mimic a list box by hiding grid lines and headers, and provides a method to set the list box values. ```python from tksheet import Sheet import tkinter as tk class Sheet_Listbox(Sheet): def __init__(self, parent, values = []): Sheet.__init__(self, parent = parent, show_horizontal_grid = False, show_vertical_grid = False, show_header = False, show_row_index = False, show_top_left = False, empty_horizontal = 0, empty_vertical = 0) if values: self.values(values) def values(self, values = []): self.set_sheet_data([[v] for v in values], reset_col_positions = False, reset_row_positions = False, redraw = False, verify = False) self.set_all_cell_sizes_to_text() class demo(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.grid_columnconfigure(0, weight = 1) self.grid_rowconfigure(0, weight = 1) self.listbox = Sheet_Listbox(self, values = [f"_________ Item {i} _________" for i in range(2000)]) self.listbox.grid(row = 0, column = 0, sticky = "nswe") #self.listbox.values([f"new values {i}" for i in range(50)]) set values app = demo() app.mainloop() ``` -------------------------------- ### Create Custom Formatters for tksheet Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Illustrates how to create and use custom formatters in tksheet for displaying data in specific ways. It imports various formatter functions and related utilities from the tksheet library. ```python from tksheet import ( Sheet, formatter, float_formatter, int_formatter, percentage_formatter, bool_formatter, truthy, falsy, num2alpha, ) import tkinter as tk from datetime import datetime, date from dateutil import parser, tz from math import ceil import re date_replace = re.compile("|".join(re.escape(char) for char in "()[]<>" )) ``` -------------------------------- ### Get Selected Rows Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Get the indices of the currently selected rows. Returns displayed indices. ```APIDOC ## GET /selected/rows ### Description Get the indices of the currently selected rows. Returns displayed indices. ### Method GET ### Endpoint /selected/rows ### Parameters #### Query Parameters - **get_cells** (bool, optional) - Whether to get cells as rows. - **get_cells_as_rows** (bool, optional) - Whether to get cells as rows. - **return_tuple** (bool, optional) - Whether to return the result as a tuple. ### Response #### Success Response (200) - **tuple[int] | tuple[tuple[int, int]] | set[int] | set[tuple[int, int]]** - A collection of selected row indices or cell coordinates. #### Response Example ```json [1, 3, 5] ``` ``` -------------------------------- ### Get Currently Selected Cell Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Get the currently selected cell. This returns displayed indices and can be converted to data indices if needed. ```APIDOC ## GET /selected/cell ### Description Get the currently selected cell. This is always a single cell of displayed indices. ### Method GET ### Endpoint /selected/cell ### Response #### Success Response (200) - **tuple | Selected** - A namedtuple of (row, column, type_, box, iid, fill_iid) or an empty tuple if nothing is selected. #### Response Example ```json { "row": 5, "column": 3, "type_": "cells", "box": [5, 3, 6, 4], "iid": "canvas_item_id_1", "fill_iid": "fill_canvas_item_id_1" } ``` ``` -------------------------------- ### Initialize and Configure tksheet with Tkinter Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index This Python code demonstrates how to initialize a tksheet Sheet widget within a Tkinter application. It shows how to set initial data, apply a theme, configure dimensions, and enable various bindings for user interaction. It also includes methods for handling user edits and modifying sheet content. ```python from tksheet import Sheet, num2alpha import tkinter as tk class demo(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self.frame = tk.Frame(self) self.frame.grid_columnconfigure(0, weight=1) self.frame.grid_rowconfigure(0, weight=1) # create an instance of Sheet() self.sheet = Sheet( # set the Sheets parent widget self.frame, # optional: set the Sheets data at initialization data=[[f"Row {r}, Column {c}\nnewline1\nnewline2" for c in range(20)] for r in range(100)], theme="light green", height=520, width=1000, ) # enable various bindings self.sheet.enable_bindings("all", "edit_index", "edit_header") # set a user edit validation function # AND bind all sheet modification events to a function # chained as two functions # more information at: # #bind-and-validate-user-cell-edits self.sheet.edit_validation(self.validate_edits).bind("<>", self.sheet_modified) # add some new commands to the in-built right click menu # setting data self.sheet.popup_menu_add_command( "Say Hello", self.say_hello, index_menu=False, header_menu=False, empty_space_menu=False, ) # getting data self.sheet.popup_menu_add_command( "Print some data", self.print_data, empty_space_menu=False, ) # overwrite Sheet data self.sheet.popup_menu_add_command("Reset Sheet data", self.reset) # set the header self.sheet.popup_menu_add_command( "Set header data", self.set_header, table_menu=False, index_menu=False, empty_space_menu=False, ) # set the index self.sheet.popup_menu_add_command( "Set index data", self.set_index, table_menu=False, header_menu=False, empty_space_menu=False, ) self.frame.grid(row=0, column=0, sticky="nswe") self.sheet.grid(row=0, column=0, sticky="nswe") def validate_edits(self, event): # print (event) if event.eventname.endswith("header"): return event.value + " edited header" elif event.eventname.endswith("index"): return event.value + " edited index" else: if not event.value: return "EMPTY" return event.value[:3] def say_hello(self): current_selection = self.sheet.get_currently_selected() if current_selection: box = (current_selection.row, current_selection.column) # set cell data, end user Undo enabled # more information at: # #setting-sheet-data self.sheet[box].options(undo=True).data = "Hello World!" # highlight the cell for 2 seconds self.highlight_area(box) def print_data(self): for box in self.sheet.get_all_selection_boxes(): # get user selected area sheet data # more information at: # #getting-sheet-data data = self.sheet[box].data for row in data: print(row) def reset(self): # overwrites sheet data, more information at: # #setting-sheet-data self.sheet.set_sheet_data([[f"Row {r}, Column {c}\nnewline1\nnewline2" for c in range(20)] for r in range(100)]) # reset header and index self.sheet.headers([]) self.sheet.index([]) def set_header(self): self.sheet.headers( [f"Header {(letter := num2alpha(i))} - {i + 1}\nHeader {letter} 2nd line!" for i in range(20)] ) def set_index(self): self.sheet.set_index_width() self.sheet.row_index( [f"Index {(letter := num2alpha(i))} - {i + 1}\nIndex {letter} 2nd line!" for i in range(100)] ) def sheet_modified(self, event): # uncomment below if you want to take a look at the event object # print ("The sheet was modified! Event object:") # for k, v in event.items(): # print (k, ":", v) # print ("\n") # otherwise more information at: # #event-data # highlight the modified cells briefly if event.eventname.startswith("move"): for box in self.sheet.get_all_selection_boxes(): self.highlight_area(box) else: pass def highlight_area(self, box): self.sheet.highlight_cells(rows=(box[0], box[0]), cols=(box[1], box[1]), bg="#FF0000", fg="#FFFFFF", time_interval=2000) app = demo() app.mainloop() ``` -------------------------------- ### Basic tksheet Initialization Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Demonstrates the fundamental way to initialize a tksheet widget within a tkinter application. It requires a parent tkinter widget. ```python from tksheet import Sheet # Assuming 'my_frame_widget' is an existing tkinter widget sheet = Sheet(my_frame_widget) ``` -------------------------------- ### Highlight Columns with Options Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Allows highlighting of specified columns with customizable background and foreground colors. Options include highlighting the column header, controlling redraw, and overwriting existing highlights. ```python highlight_columns( columns: Iterator[int] | int, bg: bool | None | str = False, fg: bool | None | str = False, highlight_header: bool = True, redraw: bool = True, overwrite: bool = True, ) -> Sheet ``` -------------------------------- ### Configure Edit and Action Menu Items Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Define labels, accelerators, images, and compound display modes for various actions like editing cells, headers, indexes, and performing cut, copy, paste, and delete operations. These options are used to build context menus and toolbars. ```python "edit_header_label": "Edit header", "edit_header_accelerator": "", "edit_header_image": tk.PhotoImage(data=ICON_EDIT), "edit_header_compound": "left", "cut_label": "Cut", "cut_accelerator": "Ctrl+X", "cut_image": tk.PhotoImage(data=ICON_CUT), "cut_compound": "left", "copy_label": "Copy", "copy_accelerator": "Ctrl+C", "copy_image": tk.PhotoImage(data=ICON_COPY), "copy_compound": "left", "paste_label": "Paste", "paste_accelerator": "Ctrl+V", "paste_image": tk.PhotoImage(data=ICON_PASTE), "paste_compound": "left", "delete_label": "Delete", "delete_accelerator": "Del", "delete_image": tk.PhotoImage(data=ICON_CLEAR), "delete_compound": "left" ``` -------------------------------- ### Custom Right Click and Text Editor Validation Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Illustrates how to add custom commands to the right-click popup menu and how to validate user input in the text editor. The example adds a 'Say Hello' command and removes spaces from any edited cell content. It requires the tkinter library. ```python from tksheet import Sheet import tkinter as tk class demo(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self.frame = tk.Frame(self) self.frame.grid_columnconfigure(0, weight=1) self.frame.grid_rowconfigure(0, weight=1) self.sheet = Sheet(self.frame, data=[[f"Row {r}, Column {c}\nnewline1\nnewline2" for c in range(50)] for r in range(500)]) self.sheet.enable_bindings( "single_select", "drag_select", "edit_cell", "paste", "cut", "copy", "delete", "select_all", "column_select", "row_select", "column_width_resize", "double_click_column_resize", "arrowkeys", "row_height_resize", "double_click_row_resize", "right_click_popup_menu", "rc_select", ) self.sheet.extra_bindings("begin_edit_cell", self.begin_edit_cell) self.sheet.edit_validation(self.validate_edits) self.sheet.popup_menu_add_command("Say Hello", self.new_right_click_button) self.frame.grid(row=0, column=0, sticky="nswe") self.sheet.grid(row=0, column=0, sticky="nswe") def new_right_click_button(self, event=None): print ("Hello World!") def begin_edit_cell(self, event=None): return event.value def validate_edits(self, event): # remove spaces from any cell edits, including paste if isinstance(event.value, str) and event.value: return event.value.replace(" ", "") app = demo() app.mainloop() ``` -------------------------------- ### Get Index Cell Properties Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Retrieve options for a single cell in the index. You can get all properties or specific ones like 'highlight' or 'readonly'. ```APIDOC ## GET /index/properties ### Description Retrieve options for a single cell in the index. ### Method GET ### Endpoint /index/properties ### Parameters #### Query Parameters - **row** (int) - Required - The row index of the cell. - **key** (str, optional) - The specific property to retrieve (e.g., "highlight", "readonly"). If None, all properties are returned. ### Response #### Success Response (200) - **dict** - A dictionary containing the cell's properties. #### Response Example ```json { "highlight": "#FF0000", "readonly": true } ``` ``` -------------------------------- ### Set Sheet Data using set_data() Source: https://ragardner.github.io/tksheet/DOCUMENTATION.html/index Demonstrates how to use the `set_data()` function to populate a sheet with data, including options for undo, event emission, and redrawing. This function can set data for specific cells or ranges. ```python self.sheet.set_data( "A1", [["", "A", "B", "C"] ["1", "A1", "B1", "C1"], ["2", "A2", "B2", "C2"]], ) ```