Give a example implementation of checkboxes in tksheet. Use the following Handbook for guidance: Span Objects
In tksheet versions > 7 there are functions which utilise an object named Span. These objects are a subclass of dict but with various additions and dot notation attribute access.
Spans basically represent an contiguous area of the sheet. They can be one of three kinds:
"cell"
"row"
"column"
They can be used with some of the sheets functions such as data getting/setting and creation of things on the sheet such as dropdown boxes.
Spans store:
A reference to the Sheet() they were created with.
Variables which represent a particular range of cells and properties for accessing these ranges.
Variables which represent options for those cells.
Methods which can modify the above variables.
Methods which can act upon the table using the above variables such as highlight, format, etc.
Whether cells, rows or columns are affected will depend on the spans kind.
Creating a span
You can create a span by:
Using the span() function e.g. sheet.span("A1") represents the cell A1
or
Using square brackets on a Sheet object e.g. sheet["A1"] represents the cell A1
key you do not have to provide an argument for key, if no argument is provided then the span will be a full sheet span. Otherwise key can be the following types which are type hinted as CreateSpanTypes:
None
str e.g. sheet.span("A1:F1")
int e.g. sheet.span(0)
slice e.g. sheet.span(slice(0, 4))
Sequence[int | None, int | None] representing a cell of row, column e.g. sheet.span(0, 0)
Sequence[Sequence[int | None, int | None], Sequence[int | None, int | None]] representing sheet.span(start row, start column, up to but not including row, up to but not including column) e.g. sheet.span(0, 0, 2, 2)
Span e.g sheet.span(another_span)
type_ (str) must be either an empty string "" or one of the following: "format", "highlight", "dropdown", "checkbox", "readonly", "align".
name (str) used for named spans or for identification. If no name is provided then a name is generated for the span which is based on an internal integer ticker and then converted to a string in the same way column names are.
table (bool) when True will make all functions used with the span target the main table as well as the header/index if those are True.
index (bool) when True will make all functions used with the span target the index as well as the table/header if those are True.
header (bool) when True will make all functions used with the span target the header as well as the table/index if those are True.
tdisp (bool) is used by data getting functions that utilize spans and when True the function retrieves screen displayed data for the table, not underlying cell data.
idisp (bool) is used by data getting functions that utilize spans and when True the function retrieves screen displayed data for the index, not underlying cell data.
hdisp (bool) is used by data getting functions that utilize spans and when True the function retrieves screen displayed data for the header, not underlying cell data.
transposed (bool) is used by data getting and setting functions that utilize spans. When True:
Returned sublists from data getting functions will represent columns rather than rows.
Data setting functions will assume that a single sequence is a column rather than row and that a list of lists is a list of columns rather than a list of rows.
ndim (int) is used by data getting functions that utilize spans, it must be either 0 or 1 or 2.
0 is the default setting which will make the return value vary based on what it is. For example if the gathered data is only a single cell it will return a value instead of a list of lists with a single list containing a single value. A single row will be a single list.
1 will force the return of a single list as opposed to a list of lists.
2 will force the return of a list of lists.
convert (None, Callable) can be used to modify the data using a function before returning it. The data sent to the convert function will be as it was before normally returning (after ndim has potentially modified it).
undo (bool) is used by data modifying functions that utilize spans. When True and if undo is enabled for the sheet then the end user will be able to undo/redo the modification.
emit_event when True and when using data setting functions that utilize spans causes a "<<SheetModified>> event to occur if it has been bound, see here for more information on binding this event.
widget (object) is the reference to the original sheet which created the span. This can be changed to a different sheet if required e.g. my_span.widget = new_sheet.
expand (None, str) must be either None or:
"table"/"both" expand the span both down and right from the span start to the ends of the table.
"right" expand the span right to the end of the table x axis.
"down" expand the span downwards to the bottom of the table y axis.
formatter_options (dict, None) must be either None or dict. If providing a dict it must be the same structure as used in format functions, see here for more information. Used to turn the span into a format type span which:
When using get_data() will format the returned data.
When using set_data() will format the data being set but NOT create a new formatting rule on the sheet.
**kwargs you can provide additional keyword arguments to the function for example those used in span.highlight() or span.dropdown() which are used when applying a named span to a table.
Assistant
Notes:
To create a named span see here.
Span creation syntax
When creating a span using the below methods:
strs use excel syntax and the indexing rule of up to AND including.
ints use python syntax and the indexing rule of up to but NOT including.
For example python index 0 as in [0] is the first whereas excel index 1 as in "A1" is the first.
If you need to convert python indexes into column letters you can use the function num2alpha importable from tksheet:
from tksheet import (
Sheet,
num2alpha as n2a,
)
column index five as a letter
n2a(5)
Span creation examples using square brackets
"""
EXAMPLES USING SQUARE BRACKETS
"""
span = sheet[0] # first row
span = sheet["1"] # first row
span = sheet[0:2] # first two rows
span = sheet["1:2"] # first two rows
span = sheet[:2] # first two rows
span = sheet[":2"] # first two rows
""" THESE TWO HAVE DIFFERENT OUTCOMES """
span = sheet[2:] # all rows after and not inlcuding python index 1
span = sheet["2:"] # all rows after and not including python index 0
span = sheet["A"] # first column
span = sheet["A:C"] # first three columns
span = sheet["A1:2"]
span = sheet[0, 0, 2, None]
"""
["A1:2"]
All the cells starting from (0, 0)
expanding down to include row 1
but not including cells beyond row
1 and expanding out to include all
columns
A B C D
1 x x x x
2 x x x x
3
4
...
"""
span = sheet["A1:B"]
span = sheet[0, 0, None, 2]
"""
["A1:B"]
All the cells starting from (0, 0)
expanding out to include column 1
but not including cells beyond column
1 and expanding down to include all
rows
A B C D
1 x x
2 x x
3 x x
4 x x
...
"""
""" GETTING AN EXISTING NAMED SPAN """
you can retrieve an existing named span quickly by surrounding its name in <> e.g.
named_span_retrieval = sheet[""]
Span creation examples using sheet.span()
"""
EXAMPLES USING span()
"""
"""
USING NO ARGUMENTS
"""
sheet.span() # entire sheet, in this case not including header or index
"""
USING ONE ARGUMENT
str or int or slice()
"""
with one argument you can use the same string syntax used for square bracket span creation
sheet.span("A1")
sheet.span(0) # row at python index 0, all columns
sheet.span(slice(0, 2)) # rows at python indexes 0 and 1, all columns
sheet.span(":") # entire sheet
"""
USING TWO ARGUMENTS
int | None, int | None
or
(int | None, int | None), (int | None, int | None)
"""
sheet.span(0, 0) # row 0, column 0 - the first cell
sheet.span(0, None) # row 0, all columns
sheet.span(None, 0) # column 0, all rows
sheet.span((0, 0), (1, 1)) # row 0, column 0 - the first cell
sheet.span((0, 0), (None, 2)) # rows 0 - end, columns 0 and 1
"""
USING FOUR ARGUMENTS
int | None, int | None, int | None, int | None
"""
sheet.span(0, 0, 1, 1) # row 0, column 0 - the first cell
sheet.span(0, 0, None, 2) # rows 0 - end, columns 0 and 1
Span properties
Spans have a few @property functions:
span.kind
span.rows
span.columns
Get a spans kind
span.kind
Returns either "cell", "row" or "column".
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"
Get span rows and columns
span.rows
span.columns
Returns a SpanRange object. The below examples are for span.rows but you can use span.columns for the spans columns exactly the same way.
use as an iterator
span = sheet.span("A1:C4")
for row in span.rows:
pass
Spans have the following methods, all of which return the span object itself so you can chain the functions e.g. span.options(undo=True).clear().bg = "indianred1"
Modify a spans attributes
Note: that if None is used for any of the following parameters then that Spans attribute will be unchanged.
type_ (str, None) if not None then must be either an empty string "" or one of the following: "format", "highlight", "dropdown", "checkbox", "readonly", "align".
name (str, None) is used for named spans or for identification.
table (bool, None) when True will make all functions used with the span target the main table as well as the header/index if those are True.
index (bool, None) when True will make all functions used with the span target the index as well as the table/header if those are True.
header (bool, None) when True will make all functions used with the span target the header as well as the table/index if those are True.
tdisp (bool, None) is used by data getting functions that utilize spans and when True the function retrieves screen displayed data for the table, not underlying cell data.
idisp (bool, None) is used by data getting functions that utilize spans and when True the function retrieves screen displayed data for the index, not underlying cell data.
hdisp (bool, None) is used by data getting functions that utilize spans and when True the function retrieves screen displayed data for the header, not underlying cell data.
transposed (bool, None) is used by data getting and setting functions that utilize spans. When True:
Returned sublists from data getting functions will represent columns rather than rows.
Data setting functions will assume that a single sequence is a column rather than row and that a list of lists is a list of columns rather than a list of rows.
ndim (int, None) is used by data getting functions that utilize spans, it must be either 0 or 1 or 2.
0 is the default setting which will make the return value vary based on what it is. For example if the gathered data is only a single cell it will return a value instead of a list of lists with a single list containing a single value. A single row will be a single list.
1 will force the return of a single list as opposed to a list of lists.
2 will force the return of a list of lists.
convert (Callable, None) can be used to modify the data using a function before returning it. The data sent to the convert function will be as it was before normally returning (after ndim has potentially modified it).
undo (bool, None) is used by data modifying functions that utilize spans. When True and if undo is enabled for the sheet then the end user will be able to undo/redo the modification.
emit_event (bool, None) is used by data modifying functions that utilize spans. When True causes a "<<SheetModified>> event to occur if it has been bound, see here for more information.
widget (object) is the reference to the original sheet which created the span. This can be changed to a different sheet if required e.g. my_span.widget = new_sheet.
expand (str, None) must be either None or:
"table"/"both" expand the span both down and right from the span start to the ends of the table.
"right" expand the span right to the end of the table x axis.
"down" expand the span downwards to the bottom of the table y axis.
formatter_options (dict, None) must be either None or dict. If providing a dict it must be the same structure as used in format functions, see here for more information. Used to turn the span into a format type span which:
When using get_data() will format the returned data.
When using set_data() will format the data being set but NOT create a new formatting rule on the sheet.
**kwargs you can provide additional keyword arguments to the function for example those used in span.highlight() or span.dropdown() which are used when applying a named span to a table.
This function returns the span instance itself (self).
entire sheet
span = sheet["A1"].options(expand="both")
column A
span = sheet["A1"].options(expand="down")
row 0
span = sheet["A1"].options(
expand="right",
ndim=1, # to return a single list when getting data
)
All of a spans modifiable attributes are listed here:
from_r (int) represents which row the span starts at, must be a positive int.
from_c (int) represents which column the span starts at, must be a positive int.
upto_r (int, None) represents which row the span ends at, must be a positive int or None. None means always up to and including the last row.
upto_c (int, None) represents which column the span ends at, must be a positive int or None. None means always up to and including the last column.
type_ (str) must be either an empty string "" or one of the following: "format", "highlight", "dropdown", "checkbox", "readonly", "align".
name (str) used for named spans or for identification. If no name is provided then a name is generated for the span which is based on an internal integer ticker and then converted to a string in the same way column names are.
table (bool) when True will make all functions used with the span target the main table as well as the header/index if those are True.
index (bool) when True will make all functions used with the span target the index as well as the table/header if those are True.
header (bool) when True will make all functions used with the span target the header as well as the table/index if those are True.
tdisp (bool) is used by data getting functions that utilize spans and when True the function retrieves screen displayed data for the table, not underlying cell data.
idisp (bool) is used by data getting functions that utilize spans and when True the function retrieves screen displayed data for the index, not underlying cell data.
hdisp (bool) is used by data getting functions that utilize spans and when True the function retrieves screen displayed data for the header, not underlying cell data.
transposed (bool) is used by data getting and setting functions that utilize spans. When True:
Returned sublists from data getting functions will represent columns rather than rows.
Data setting functions will assume that a single sequence is a column rather than row and that a list of lists is a list of columns rather than a list of rows.
ndim (int) is used by data getting functions that utilize spans, it must be either 0 or 1 or 2.
0 is the default setting which will make the return value vary based on what it is. For example if the gathered data is only a single cell it will return a value instead of a list of lists with a single list containing a single value. A single row will be a single list.
1 will force the return of a single list as opposed to a list of lists.
2 will force the return of a list of lists.
convert (None, Callable) can be used to modify the data using a function before returning it. The data sent to the convert function will be as it was before normally returning (after ndim has potentially modified it).
undo (bool) is used by data modifying functions that utilize spans. When True and if undo is enabled for the sheet then the end user will be able to undo/redo the modification.
emit_event (bool) is used by data modifying functions that utilize spans. When True causes a "<<SheetModified>> event to occur if it has been bound, see here for more information.
widget (object) is the reference to the original sheet which created the span. This can be changed to a different sheet if required e.g. my_span.widget = new_sheet.
kwargs a dict containing keyword arguments relevant for functions such as span.highlight() or span.dropdown() which are used when applying a named span to a table.
If necessary you can also modify these attributes the same way you would an objects. e.g.
span now takes in all columns, including A
span = self.sheet("A")
span.upto_c = None
span now adds to sheets undo stack when using data modifying functions that use spans
span = self.sheet("A")
span.undo = True
Using a span to format data
Formats table data, see the help on formatting for more information. Note that using this function also creates a format rule for the affected table cells.
These examples show the formatting of the entire sheet (not including header and index) as int and creates a format rule for all currently existing cells. Named spans are required to create a rule for all future existing cells as well, for example those created by the end user inserting rows or columns.
Using a span to delete data format rules
Delete any currently existing format rules for parts of the table that are covered by the span. Should not be used where there are data formatting rules created by named spans, see Named spans for more information.
Delete any currently existing highlights for parts of the sheet that are covered by the span. Should not be used where there are highlights created by named spans, see Named spans for more information.
Delete dropdown boxes for parts of the sheet that are covered by the span. Should not be used where there are dropdown box rules created by named spans, see Named spans for more information.
edit_data when True edits the underlying cell data to either checked if checked is a bool or tries to convert the existing cell data to a bool.
checked is the initial creation value to set the box to, if None then and edit_data is True then it will try to convert the underlying cell data to a bool.
state can be "normal" or "disabled". If "disabled" then color will be same as table grid lines, else it will be the cells text color.
check_function can be used to trigger a function when the user clicks a checkbox.
text displays text next to the checkbox in the cell, but will not be used as data, data will either be True or False.
Delete check boxes for parts of the sheet that are covered by the span. Should not be used where there are check box rules created by named spans, see Named spans for more information.
Create a readonly rule for parts of the table that are covered by the span.
span.readonly(readonly: bool = True) -> Span
Using span.readonly(False) deletes any existing readonly rules for the span. Should not be used where there are readonly rules created by named spans, see Named spans for more information.
Using a span to create text alignment rules
Create a text alignment rule for parts of the sheet that are covered by the span.
align (str, None) must be either:
None - clears the alignment rule
"c", "center", "centre"
"w", "west", "left"
"e", "east", "right"
Example:
sheet["D"].align("right")
There are two ways to create alignment rules using a span:
Method 1 example using .align():
column D right text alignment
sheet["D"].align("right")
the same but after having saved a span
my_span = sheet["D"]
my_span.align("right")
Method 2 example using .align = :
column D right text alignment
sheet["D"].align = "right"
the same but after having saved a span
my_span = sheet["D"]
my_span.align = "right"
Using a span to delete text alignment rules
Delete text alignment rules for parts of the sheet that are covered by the span. Should not be used where there are alignment rules created by named spans, see Named spans for more information.
undo (bool, None) When True if undo is enabled for the end user they will be able to undo the clear change.
emit_event when True causes a "<<SheetModified>> event to occur if it has been bound, see here for more information.
Example:
clears column D
sheet["D"].clear()
Using a span to tag cells
Tag cells, rows or columns depending on the spans kind, more information on tags here.
tag(*tags) -> Span
Notes:
If span.kind is "cell" then cells will be tagged, if it's a row span then rows will be and so for columns.
Example:
tags rows 2, 3, 4 with "hello world"
sheet[2:5].tag("hello world")
Using a span to untag cells
Remove all tags from cells, rows or columns depending on the spans kind, more information on tags here.
untag() -> Span
Notes:
If span.kind is "cell" then cells will be untagged, if it's a row span then rows will be and so for columns.
Example:
tags rows 2, 3, 4 with "hello" and "bye"
sheet[2:5].tag("hello", "bye")
removes both "hello" and "bye" tags from rows 2, 3, 4
sheet[2:5].untag()
Set the spans orientation
The attribute span.transposed (bool) is used by data getting and setting functions that utilize spans. When True: - Returned sublists from data getting functions will represent columns rather than rows. - Data setting functions will assume that a single sequence is a column rather than row and that a list of lists is a list of columns rather than a list of rows.
You can toggle the transpotition of the span by using:
span.transpose() -> Span
If the attribute is already True this makes it False and vice versa.
span = sheet["A:D"].transpose()
this span is now transposed
print (span.transposed)
prints True
span.transpose()
this span is no longer transposed
print (span.transposed)
prints False
Expand the spans area
Expand the spans area either all the way to the right (x axis) or all the way down (y axis) or both.
span.expand(direction: str = "both") -> Span
direction (None, str) must be either None or:
"table"/"both" expand the span both down and right from the span start to the ends of the table.
"right" expand the span right to the end of the table x axis.
"down" expand the span downwards to the bottom of the table y axis.
Named Spans
Named spans are like spans but with a type, some keyword arguments saved in span.kwargs and then created by using a Sheet() function. Like spans, named spans are also contiguous areas of the sheet.
Named spans can be used to:
Create options (rules) for the sheet which will expand/contract when new cells are added/removed. For example if a user were to insert rows in the middle of some already highlighted rows:
With ordinary row highlights the newly inserted rows would NOT be highlighted.
With named span row highlights the newly inserted rows would also be highlighted.
Quickly delete an existing option from the table whereas an ordinary span would not keep track of where the options have been moved.
Note that generally when a user moves rows/columns around the dimensions of the named span essentially move with either end of the span:
The new start of the span will be wherever the start row/column moves.
The new end of the span will be wherever the end row/column moves. The exceptions to this rule are when a span is expanded or has been created with Nones or the start of 0 and no end or end of None.
For the end user, when a span is just a single row/column (and is not expanded/unlimited) it cannot be expanded but it can be deleted if the row/column is deleted.
Creating a named span
For a span to become a named span it needs:
One of the following type_s: "format", "highlight", "dropdown", "checkbox", "readonly", "align".
Relevant keyword arguments e.g. if the type_ is "highlight" then arguments for sheet.highlight() found here.
After a span has the above items the following function has to be used to make it a named span and create the options on the sheet:
named_span(span: Span)
"""
Adds a named span to the sheet
Returns the span
"""
span must be an existing span with:
a name (a name is automatically generated upon span creation if one is not provided).
a type_ as described above.
keyword arguments as described above.
Will always keep the entire sheet formatted as int no matter how many rows/columns are inserted
span2 = self.sheet.span(
":",
# you don't have to provide a type_ when using the formatter_kwargs argument
formatter_options=int_formatter(),
)
self.sheet.named_span(span2)
Deleting a named span
To delete a named span you simply have to provide the name.
Span objects (more information here) can be used to create check boxes for cells, rows, columns, the entire sheet, headers and the index.
You can use either of the following methods:
Using a span method e.g. span.checkbox() more information here.
Using a sheet method e.g. sheet.checkbox(Span)
Or if you need user inserted row/columns in the middle of areas with check boxes to also have check boxes you can use named spans, more information here.
Whether check boxes are created for cells, rows or columns depends on the kind of span.
check_function (Callable, None) requires either None or a function. The function you use needs at least one argument because when the checkbox is clicked it will send information to your function about the clicked checkbox.
Use highlight_cells() or rows or columns to change the color of the checkbox.
Check boxes are always left aligned despite any align settings.
Parameters:
key (CreateSpanTypes) either a span or a type which can create a span. See here for more information on the types that can create a span.
edit_data when True edits the underlying cell data to either checked if checked is a bool or tries to convert the existing cell data to a bool.
checked is the initial creation value to set the box to, if None then and edit_data is True then it will try to convert the underlying cell data to a bool.
state can be "normal" or "disabled". If "disabled" then color will be same as table grid lines, else it will be the cells text color.
check_function can be used to trigger a function when the user clicks a checkbox.
text displays text next to the checkbox in the cell, but will not be used as data, data will either be True or False.
Example:
self.sheet.checkbox(
"D",
checked=True,
)
Deleting check boxes
If the check boxes were created by a named span then the named span must be deleted, more information here.
Otherwise you can use either of the following methods to delete/remove check boxes:
Using a span method e.g. span.del_checkbox() more information here.
Using a sheet method e.g. sheet.del_checkbox(Span) details below:
Certainly! Below is a comprehensive example demonstrating how to implement checkboxes in a tksheet using Span objects as described in the provided handbook. This example showcases creating a spreadsheet with checkboxes in a specific column, handling checkbox events, and utilizing named spans for dynamic behavior.
Prerequisites
Before running the example, ensure you have tksheet installed. You can install it using pip:
pip install tksheet
Example Implementation
import tkinter as tk
from tksheet import Sheet, SpanObject
def on_checkbox_click(event, sheet, row, column, value):
"""
Callback function when a checkbox is clicked.
"""
print(f"Checkbox at row {row}, column {column} clicked. New value: {value}")
def main():
# Initialize the main application window
root = tk.Tk()
root.title("tksheet Checkboxes Example")
root.geometry("600x400")
# Sample data for the sheet
data = [
["Item", "Description", "Select"],
["1", "Apple", False],
["2", "Banana", True],
["3", "Cherry", False],
["4", "Date", True],
["5", "Elderberry", False],
]
# Create the Sheet widget
sheet = Sheet(
root,
data=data,
headers=["ID", "Fruit", "Select"],
show_header=True,
show_grid=True,
width=600,
height=400,
)
sheet.pack(expand=True, fill='both')
# Define the column index where checkboxes will be placed (0-based)
checkbox_column = 2 # Third column ("Select")
# Create a span for the checkbox column (excluding header)
checkbox_span = sheet.span(slice(1, len(data)), checkbox_column)
# Add checkboxes to the span
checkbox_span.checkbox(
edit_data=True,
checked=True,
state="normal",
check_function=lambda e, r=1, c=checkbox_column: on_checkbox_click(e, sheet, r, c, e),
text="",
)
# Optionally, make the span a named span for dynamic behavior
sheet.named_span(
checkbox_span.options(
type_="checkbox",
name="selection_checkbox",
expand="both", # Expand to include new rows/columns
)
)
# Example: Adding a button to retrieve checkbox states
def get_checkbox_states():
checkbox_data = sheet.get_checkboxes()
print("Current checkbox states:")
for key, state in checkbox_data.items():
print(f"Cell {key}: {state}")
btn_frame = tk.Frame(root)
btn_frame.pack(fill='x', padx=10, pady=10)
get_states_btn = tk.Button(
btn_frame,
text="Get Checkbox States",
command=get_checkbox_states
)
get_states_btn.pack(side='left')
# Run the Tkinter event loop
root.mainloop()
if __name__ == "__main__":
main()
Explanation of the Example
Importing Modules:
tkinter for GUI components.
tksheet.Sheet and tksheet.SpanObject for creating and managing the spreadsheet and span objects.
Callback Function:
on_checkbox_click: This function is triggered whenever a checkbox is clicked. It prints the row, column, and new value of the clicked checkbox.
Initializing the Application Window:
A Tk window is created with a title and specified geometry.
Sample Data:
A list of lists representing the rows and columns of the sheet. The third column ("Select") contains boolean values indicating the initial state of the checkboxes.
Creating the Sheet Widget:
The Sheet widget is instantiated with the sample data, headers, and visual configurations like showing headers and gridlines. It's packed to expand and fill the available space.
Defining the Checkbox Column:
The variable checkbox_column is set to 2, indicating the third column where checkboxes will be placed.
Creating a Span for Checkboxes:
A Span is created for the checkbox column excluding the header (slice(1, len(data)) ensures that the header row is excluded).
The span is limited to the specified checkbox_column.
Adding Checkboxes to the Span:
The checkbox method is called on the span to add checkboxes.
Parameters:
edit_data=True: The underlying cell data will be updated based on the checkbox state.
checked=True: Initializes checkboxes as checked.
state="normal": Enables the checkboxes.
check_function: A lambda function that calls on_checkbox_click with relevant parameters.
text="": No additional text displayed next to the checkbox.
Creating a Named Span:
The span is converted into a named span ("selection_checkbox") using sheet.named_span. This allows dynamic behavior, such as automatically adding checkboxes to new rows or columns added by the user.
The expand="both" parameter ensures that the span expands both vertically and horizontally with the sheet.
Retrieving Checkbox States:
A button labeled "Get Checkbox States" is added below the sheet.
When clicked, it retrieves the current states of all checkboxes using sheet.get_checkboxes() and prints them to the console.
Running the Application:
The mainloop starts the Tkinter event loop, displaying the window and responding to user interactions.
Features Demonstrated
Adding Checkboxes to a Specific Column:
The example adds checkboxes to the third column of the sheet, excluding the header.
Handling Checkbox Click Events:
A callback function is linked to checkbox clicks, allowing you to perform actions based on user interactions.
Using Named Spans for Dynamic Behavior:
By naming the span and setting expand="both", the checkboxes automatically apply to new rows or columns added to the sheet.
Retrieving Checkbox States:
A button demonstrates how to programmatically access the current states of all checkboxes in the sheet.
Running the Example
Save the provided code to a file, for example, tksheet_checkboxes.py.
Ensure you have tksheet installed.
Run the script using Python:
python tksheet_checkboxes.py
A window will appear displaying a table with a "Select" column containing checkboxes. You can interact with the checkboxes, add new rows (if permitted by tksheet settings), and retrieve the current states by clicking the "Get Checkbox States" button.
Customizations
Checkbox Placement:
Modify the checkbox_column variable to place checkboxes in a different column.
Initial Checkbox States:
Change the boolean values in the data list to set initial checkbox states.
Checkbox Appearance:
Use the text parameter in the checkbox method to display text next to checkboxes.
Handling Different Events:
Customize the on_checkbox_click function to perform different actions based on checkbox interactions.
This example provides a foundational understanding of integrating checkboxes within a tksheet using Span objects. You can extend and customize it further based on your specific application requirements.