pytktable 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,71 @@
1
+ Metadata-Version: 2.4
2
+ Name: pytktable
3
+ Version: 0.1.0
4
+ Summary: A spreadsheet-like table widget for tkinter, wrapping the Tcl/Tk Tktable extension.
5
+ License-Expression: BSD-2-Clause
6
+ License-File: LICENSE.md
7
+ Keywords: tkinter,tk,tcl,table,tktable,widget,gui
8
+ Author: Guilherme Polo
9
+ Author-email: ggpolo@gmail.com
10
+ Maintainer: nbro
11
+ Maintainer-email: nbrosoftware@outlook.com
12
+ Requires-Python: >=3.11
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Environment :: X11 Applications
15
+ Classifier: Environment :: MacOS X
16
+ Classifier: Environment :: Win32 (MS Windows)
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Topic :: Software Development :: User Interfaces
19
+ Classifier: Topic :: Software Development :: Libraries :: Tcl Extensions
20
+ Classifier: Operating System :: MacOS
21
+ Classifier: Operating System :: Microsoft :: Windows
22
+ Classifier: Operating System :: POSIX :: Linux
23
+ Classifier: Programming Language :: Python :: 3
24
+ Classifier: Programming Language :: Python :: 3 :: Only
25
+ Classifier: Programming Language :: Python :: 3.11
26
+ Classifier: Programming Language :: Python :: 3.12
27
+ Classifier: Programming Language :: Python :: 3.13
28
+ Classifier: Programming Language :: Python :: 3.14
29
+ Classifier: Programming Language :: Python :: 3.15
30
+ Project-URL: Documentation, https://nbro.github.io/tktable/
31
+ Project-URL: Repository, https://github.com/nbro/tktable
32
+ Project-URL: changelog, https://github.com/nbro/tktable/blob/main/CHANGELOG.md
33
+ Project-URL: issues, https://github.com/nbro/tktable/issues
34
+ Description-Content-Type: text/markdown
35
+
36
+ # pytktable
37
+
38
+ [![PyPI](https://img.shields.io/pypi/v/pytktable)](https://pypi.org/project/pytktable/)
39
+ [![Python](https://img.shields.io/pypi/pyversions/pytktable)](https://pypi.org/project/pytktable/)
40
+ [![Tests](https://github.com/nbro/tktable/actions/workflows/tests.yml/badge.svg?branch=main)](https://github.com/nbro/tktable/actions/workflows/tests.yml)
41
+ [![Docs](https://github.com/nbro/tktable/actions/workflows/docs.yml/badge.svg?branch=main)](https://nbro.github.io/tktable/)
42
+ [![License](https://img.shields.io/badge/license-BSD%202--Clause-orange.svg)](LICENSE.md)
43
+
44
+ A spreadsheet-like table widget for tkinter, wrapping the Tcl/Tk
45
+ [Tktable](https://wiki.tcl-lang.org/page/Tktable) extension.
46
+
47
+ The wrapper was originally written by [Guilherme Polo](https://github.com/gpip).
48
+
49
+ ## Installation
50
+
51
+ ```sh
52
+ pip install pytktable
53
+ ```
54
+
55
+ It is imported as `tktable` (`from tktable import Table`). It also needs the Tktable extension,
56
+ which `pip` does not install: see [Installation](https://nbro.github.io/tktable/installation/)
57
+ for how to install it on your OS, and run `python -m tktable` to check that it works.
58
+
59
+ ## Documentation
60
+
61
+ <https://nbro.github.io/tktable/>: usage, API reference, development and releasing.
62
+
63
+ ## License
64
+
65
+ [BSD 2-Clause](LICENSE.md).
66
+
67
+ Copyright (c) 2008, Guilherme Polo\
68
+ Copyright (c) 2016-2026, nbro
69
+
70
+ See the [changelog](CHANGELOG.md) for what changed in this fork.
71
+
@@ -0,0 +1,9 @@
1
+ tktable/__init__.py,sha256=X-V3MuKRB8Dgi3yW23Mh31ctr0E6KU4NbzKs0f9cyIU,1439
2
+ tktable/__main__.py,sha256=Vy6GO1ydLqgA9-e8vtEdScTneocw6IgwAgqMOXGHoyI,2055
3
+ tktable/array_var.py,sha256=O_GqTP_oYtHvQvbBWcRg8psYJm6TreODzgPGzMrY4YY,2242
4
+ tktable/table.py,sha256=8y-0WUvkbFjGjDPS3n_MYirQDuQG4iqXyCj_F5NRV_o,20580
5
+ tktable/utils.py,sha256=W24ZkiXsnZKhWAp6rnQFbME9UwJMgeuR_26mQuvH0qU,2119
6
+ pytktable-0.1.0.dist-info/METADATA,sha256=pvw6EBXUQiU7OGG8uZaW9wcxtSsdIiwjlVvntadDvTk,2917
7
+ pytktable-0.1.0.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
8
+ pytktable-0.1.0.dist-info/licenses/LICENSE.md,sha256=twmz6FN1xoOCugqPviw66pIFjDNDlEN0omzAGWC-6ng,1411
9
+ pytktable-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.5.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,19 @@
1
+ # [The BSD 2-Clause License](https://opensource.org/licenses/BSD-2-Clause)
2
+
3
+ Copyright (c) 2008, Guilherme Polo
4
+
5
+ Copyright (c) 2016-2026, nbro
6
+
7
+ All rights reserved.
8
+
9
+ Redistribution and use in source and binary forms, with or without
10
+ modification, are permitted provided that the following conditions are met:
11
+
12
+ * Redistributions of source code must retain the above copyright notice,
13
+ this list of conditions and the following disclaimer.
14
+
15
+ * Redistributions in binary form must reproduce the above copyright notice,
16
+ this list of conditions and the following disclaimer in the documentation
17
+ and/or other materials provided with the distribution.
18
+
19
+ > THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
tktable/__init__.py ADDED
@@ -0,0 +1,36 @@
1
+ """A spreadsheet-like table widget for tkinter, wrapping the Tcl/Tk Tktable extension.
2
+
3
+ Why the public classes are imported lazily
4
+ ------------------------------------------
5
+ ``python -m tktable`` (the diagnostic in ``__main__.py``) always imports this file first.
6
+ ``ArrayVar`` and ``Table`` import ``tkinter`` at module level, so importing them here
7
+ eagerly would make the diagnostic crash with ``ModuleNotFoundError`` exactly when it is
8
+ most needed: when tkinter is not installed.
9
+
10
+ Instead, the module-level ``__getattr__`` below (PEP 562) imports them on first access, so
11
+ ``from tktable import Table`` works as usual, while ``python -m tktable`` never imports
12
+ tkinter until it checks for it. The ``TYPE_CHECKING`` block is never executed, but lets
13
+ type checkers, linters and IDEs see ``tktable.Table`` and ``tktable.ArrayVar``.
14
+ """
15
+
16
+ from typing import TYPE_CHECKING, Any
17
+
18
+ __all__ = ["ArrayVar", "Table"]
19
+
20
+ if TYPE_CHECKING:
21
+ from tktable.array_var import ArrayVar
22
+ from tktable.table import Table
23
+
24
+
25
+ def __getattr__(name: str) -> Any:
26
+ # Called only for attributes not yet defined in this module (see the module docstring).
27
+ # pylint: disable=import-outside-toplevel
28
+ if name == "ArrayVar":
29
+ from tktable.array_var import ArrayVar
30
+
31
+ return ArrayVar
32
+ if name == "Table":
33
+ from tktable.table import Table
34
+
35
+ return Table
36
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
tktable/__main__.py ADDED
@@ -0,0 +1,62 @@
1
+ """Diagnose whether Tktable can be used: ``python -m tktable``.
2
+
3
+ Exits with status 0 if Tktable can be found (and loaded, when a display is available),
4
+ and 1 otherwise.
5
+ """
6
+
7
+ import os
8
+ import platform
9
+ import sys
10
+
11
+
12
+ def main() -> int:
13
+ """Print diagnostic information and return the exit status."""
14
+ print(f"Python: {sys.version.split()[0]} ({platform.platform()})")
15
+
16
+ try:
17
+ import tkinter # pylint: disable=import-outside-toplevel
18
+ except ImportError as exc:
19
+ print(f"tkinter: NOT AVAILABLE ({exc})")
20
+ print("Install tkinter for your Python (e.g. `sudo apt install python3-tk`).")
21
+ return 1
22
+
23
+ # pylint: disable-next=import-outside-toplevel
24
+ from tktable.utils import TKTABLE_LIBRARY_ENV_VAR, find_tktable, load_tktable
25
+
26
+ try:
27
+ interp = tkinter.Tcl() # Tcl only: no window, so no display needed.
28
+ except tkinter.TclError as exc:
29
+ print(f"Tcl: NOT AVAILABLE ({exc})")
30
+ return 1
31
+
32
+ print(f"Tcl: {interp.call('info', 'patchlevel')}")
33
+ print(f"{TKTABLE_LIBRARY_ENV_VAR}: {os.environ.get(TKTABLE_LIBRARY_ENV_VAR, '(not set)')}")
34
+ versions = find_tktable(interp)
35
+ print(f"auto_path: {interp.call('set', 'auto_path')}")
36
+ if not versions:
37
+ print("Tktable: NOT FOUND")
38
+ print("See https://nbro.github.io/tktable/installation/")
39
+ return 1
40
+ print(f"Tktable: found version(s) {', '.join(versions)}")
41
+
42
+ try:
43
+ root = tkinter.Tk()
44
+ except tkinter.TclError as exc:
45
+ print(f"Tk: cannot start ({exc}); skipped loading Tktable")
46
+ return 0
47
+
48
+ try:
49
+ root.withdraw()
50
+ print(f"Tk: {root.call('info', 'patchlevel')}")
51
+ print(f"Tktable: loaded version {load_tktable(root)}")
52
+ except tkinter.TclError as exc:
53
+ print(f"Tktable: FOUND BUT FAILED TO LOAD ({exc})")
54
+ print("It may have been built for a different Tcl/Tk version than your Python uses.")
55
+ return 1
56
+ finally:
57
+ root.destroy()
58
+ return 0
59
+
60
+
61
+ if __name__ == "__main__":
62
+ sys.exit(main())
tktable/array_var.py ADDED
@@ -0,0 +1,64 @@
1
+ # pylint: disable=missing-function-docstring, protected-access
2
+
3
+ """
4
+ A module that contains a class for using Tcl arrays,
5
+ which are, in some instances, required by tktable.
6
+ """
7
+
8
+ import tkinter
9
+
10
+ from tktable.utils import _setup_master
11
+
12
+
13
+ class ArrayVar(tkinter.Variable):
14
+ """Class for handling Tcl arrays.
15
+
16
+ An array is actually an associative array in Tcl, so this class supports
17
+ some dict operations.
18
+ """
19
+
20
+ # pylint: disable=super-init-not-called # TODO: can this be solve more properly?
21
+ def __init__(self, master=None, name=None):
22
+ # Tkinter.Variable.__init__ is not called on purpose! I don't wanna
23
+ # see an ugly _default value in the pretty array.
24
+ self._master = _setup_master(master)
25
+ self._tk = self._master.tk
26
+ if name:
27
+ self._name = name
28
+ else:
29
+ self._name = f"PY_VAR{id(self)}"
30
+
31
+ def __del__(self):
32
+ if bool(self._tk.call("info", "exists", self._name)):
33
+ self._tk.globalunsetvar(self._name)
34
+
35
+ def __len__(self):
36
+ return int(self._tk.call("array", "size", str(self)))
37
+
38
+ def __getitem__(self, key):
39
+ return self.get(key)
40
+
41
+ def __setitem__(self, key, value):
42
+ self.set(**{str(key): value})
43
+
44
+ def names(self):
45
+ return self._tk.splitlist(self._tk.call("array", "names", self._name))
46
+
47
+ def get(self, key=None):
48
+ if key is None:
49
+ # splitlist: tkinter may return the Tcl list as a Tcl_Obj, which can't be sliced.
50
+ flatten_pairs = self._tk.splitlist(self._tk.call("array", "get", str(self)))
51
+ return dict(list(zip(flatten_pairs[::2], flatten_pairs[1::2])))
52
+ return self._tk.globalgetvar(str(self), str(key))
53
+
54
+ # pylint: disable=arguments-differ # TODO: maybe consider calling this method differently?
55
+ def set(self, **kw):
56
+ self._tk.call("array", "set", str(self), tkinter._flatten(list(kw.items())))
57
+
58
+ def unset(self, pattern=None):
59
+ """Unsets all of the elements in the array. If pattern is given, only
60
+ the elements that match pattern are unset."""
61
+ if pattern is None:
62
+ self._tk.call("array", "unset", str(self))
63
+ else:
64
+ self._tk.call("array", "unset", str(self), pattern)
tktable/table.py ADDED
@@ -0,0 +1,486 @@
1
+ # pylint: disable=missing-function-docstring, protected-access, inconsistent-return-statements
2
+
3
+
4
+ """
5
+ A module that contains a Python wrapper class for the Tcl/tk tktable widget.
6
+ """
7
+
8
+ import logging
9
+ import tkinter
10
+
11
+ from tktable.utils import _setup_master, load_tktable
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ # TODO: consider solving the inconsistent-return-statements in more appropriate ways,
16
+ # e.g. split a method into 2, etc.
17
+
18
+
19
+ class CannotUseError(RuntimeError):
20
+ """
21
+ The exception raised when you cannot use the Table because of missing dependencies.
22
+ """
23
+
24
+
25
+ # pylint: disable=too-many-public-methods
26
+ class Table(tkinter.Widget):
27
+ """Create and manipulate tables."""
28
+
29
+ _switches = (
30
+ "holddimensions",
31
+ "holdselection",
32
+ "holdtags",
33
+ "holdwindows",
34
+ "keeptitles",
35
+ "-",
36
+ )
37
+ _tabsubst_format = ("%c", "%C", "%i", "%r", "%s", "%S", "%W")
38
+ _tabsubst_commands = (
39
+ "browsecommand",
40
+ "browsecmd",
41
+ "command",
42
+ "selectioncommand",
43
+ "selcmd",
44
+ "validatecommand",
45
+ "valcmd",
46
+ )
47
+
48
+ def __init__(self, master=None, **kw):
49
+ master = _setup_master(master)
50
+
51
+ try:
52
+ load_tktable(master)
53
+ tkinter.Widget.__init__(self, master, "table", kw)
54
+ except tkinter.TclError as exc:
55
+ raise CannotUseError(
56
+ f"You cannot instantiate {self.__class__.__name__} because the Tcl/Tk "
57
+ "extension Tktable could not be loaded by your Tcl/Tk installation.\n"
58
+ "Run `python -m tktable` to diagnose the problem, and see "
59
+ "https://nbro.github.io/tktable/installation/ for how to install Tktable "
60
+ "or point the TKTABLE_LIBRARY environment variable to it."
61
+ ) from exc
62
+
63
+ def _options(self, cnf, kw=None):
64
+ if kw:
65
+ cnf = tkinter._cnfmerge((cnf, kw))
66
+ else:
67
+ cnf = tkinter._cnfmerge(cnf)
68
+ res = ()
69
+ for k, v in cnf.items():
70
+ if callable(v):
71
+ if k in self._tabsubst_commands:
72
+ v = f"{self._register(v, self._tabsubst)} {' '.join(self._tabsubst_format)}"
73
+ else:
74
+ v = self._register(v)
75
+ res += (f"-{k}", v)
76
+ return res
77
+
78
+ def _tabsubst(self, *args):
79
+ if len(args) != len(self._tabsubst_format):
80
+ return args
81
+ tk = self.tk
82
+ c, C, i, r, s, S, W = args # pylint: disable=unused-variable
83
+ e = tkinter.Event()
84
+ e.widget = self
85
+ e.c = tk.getint(c)
86
+ e.i = tk.getint(i)
87
+ e.r = tk.getint(r)
88
+ e.C = f"{e.r:d},{e.c:d}"
89
+ e.s = s
90
+ e.S = S
91
+ try:
92
+ e.W = self._nametowidget(W)
93
+ except KeyError:
94
+ e.W = None
95
+ return (e,)
96
+
97
+ def _handle_switches(self, args):
98
+ args = args or ()
99
+ return tuple(f"-{x}" for x in args if x in self._switches)
100
+
101
+ def activate(self, index):
102
+ """Set the active cell to the one indicated by index."""
103
+ self.tk.call(self._w, "activate", index)
104
+
105
+ def bbox(self, first, last=None):
106
+ """Return the bounding box for the specified cell (range) as a
107
+ 4-tuple of x, y, width and height in pixels. It clips the box to
108
+ the visible portion, if any, otherwise an empty tuple is returned."""
109
+ return self._getints(self.tk.call(self._w, "bbox", first, last)) or ()
110
+
111
+ def clear(self, option, first=None, last=None):
112
+ """This is a convenience routine to clear certain state information
113
+ managed by the table. first and last represent valid table indices.
114
+ If neither are specified, then the command operates on the whole
115
+ table."""
116
+ self.tk.call(self._w, "clear", option, first, last)
117
+
118
+ def clear_cache(self, first=None, last=None):
119
+ """Clear the specified section of the cache, if the table has been
120
+ keeping one."""
121
+ self.clear("cache", first, last)
122
+
123
+ def clear_sizes(self, first=None, last=None):
124
+ """Clear the specified row and column areas of specific height/width
125
+ dimensions. When just one index is specified, for example 2,0, that
126
+ is interpreted as row 2 and column 0."""
127
+ self.clear("sizes", first, last)
128
+
129
+ def clear_tags(self, first=None, last=None):
130
+ """Clear the specified area of tags (all row, column and cell tags)."""
131
+ self.clear("tags", first, last)
132
+
133
+ def clear_all(self, first=None, last=None):
134
+ """Perform all of the above clear functions on the specified area."""
135
+ self.clear("all", first, last)
136
+
137
+ def curselection(self, value=None):
138
+ """With no arguments, it returns the sorted indices of the currently
139
+ selected cells. Otherwise it sets all the selected cells to the given
140
+ value if there is an associated ArrayVar and the state is not
141
+ disabled."""
142
+ result = self.tk.call(self._w, "curselection", value)
143
+ if value is None:
144
+ return result
145
+
146
+ def curvalue(self, value=None):
147
+ """If no value is given, the value of the cell being edited (indexed
148
+ by active) is returned, else it is set to the given value."""
149
+ return self.tk.call(self._w, "curvalue", value)
150
+
151
+ def delete_active(self, index1, index2=None):
152
+ """Deletes text from the active cell. If only one index is given,
153
+ it deletes the character after that index, otherwise it deletes from
154
+ the first index to the second. index can be a number, insert or end."""
155
+ self.tk.call(self._w, "delete", "active", index1, index2)
156
+
157
+ def delete_cols(self, index, count=None, switches=None):
158
+ args = self._handle_switches(switches) + (index, count)
159
+ self.tk.call(self._w, "delete", "cols", *args)
160
+
161
+ def delete_rows(self, index, count=None, switches=None):
162
+ args = self._handle_switches(switches) + (index, count)
163
+ self.tk.call(self._w, "delete", "rows", *args)
164
+
165
+ def get(self, first, last=None):
166
+ """Returns the value of the cells specified by the table indices
167
+ first and (optionally) last."""
168
+ return self.tk.call(self._w, "get", first, last)
169
+
170
+ def height(self, row=None, **kwargs):
171
+ """If row and kwargs are not given, a list describing all rows for
172
+ which a width has been set is returned.
173
+ If row is given, the height of that row is returned.
174
+ If kwargs is given, then it sets the key/value pairs, where key is a
175
+ row and value represents the height for the row."""
176
+ if row is None and not kwargs:
177
+ pairs = self.tk.splitlist(self.tk.call(self._w, "height"))
178
+ return dict(pair.split() for pair in pairs)
179
+ if row is not None:
180
+ return int(self.tk.call(self._w, "height", str(row)))
181
+ args = tkinter._flatten(list(kwargs.items()))
182
+ self.tk.call(self._w, "height", *args)
183
+
184
+ def hidden(self, *args):
185
+ """When called without args, it returns all the hidden cells (those
186
+ cells covered by a spanning cell). If one index is specified, it
187
+ returns the spanning cell covering that index, if any. If multiple
188
+ indices are specified, it returns 1 if all indices are hidden cells,
189
+ 0 otherwise."""
190
+ return self.tk.call(self._w, "hidden", *args)
191
+
192
+ def icursor(self, arg=None):
193
+ """If arg is not specified, return the location of the insertion
194
+ cursor in the active cell. Otherwise, set the cursor to that point in
195
+ the string.
196
+
197
+ 0 is before the first character, you can also use insert or end for
198
+ the current insertion point or the end of the text. If there is no
199
+ active cell, or the cell or table is disabled, this will return -1."""
200
+ return self.tk.call(self._w, "icursor", arg)
201
+
202
+ def index(self, index, rc=None):
203
+ """Return the integer cell coordinate that corresponds to index in the
204
+ form row, col. If rc is specified, it must be either 'row' or 'col' so
205
+ only the row or column index is returned."""
206
+ res = self.tk.call(self._w, "index", index, rc)
207
+ if rc is None:
208
+ return res
209
+ return int(res)
210
+
211
+ def insert_active(self, index, value):
212
+ """The value is a text string which is inserted at the index position
213
+ of the active cell. The cursor is then positioned after the new text.
214
+ index can be a number, insert or end."""
215
+ self.tk.call(self._w, "insert", "active", index, value)
216
+
217
+ def insert_cols(self, index, count=None, switches=None):
218
+ args = self._handle_switches(switches) + (index, count)
219
+ self.tk.call(self._w, "insert", "cols", *args)
220
+
221
+ def insert_rows(self, index, count=None, switches=None):
222
+ args = self._handle_switches(switches) + (index, count)
223
+ self.tk.call(self._w, "insert", "rows", *args)
224
+
225
+ # def postscript(self, **kwargs):
226
+ # """Skip this command if you are under Windows.
227
+ #
228
+ # Accepted options:
229
+ # colormap, colormode, file, channel, first, fontmap, height,
230
+ # last, pageanchor, pageheight, pagewidth, pagex, pagey, rotate,
231
+ # width, x, y
232
+ # """
233
+ # args = ()
234
+ # for key, val in kwargs.iteritems():
235
+ # args += ('-%s' % key, val)
236
+ #
237
+ # return self.tk.call(self._w, 'postscript', *args)
238
+
239
+ def reread(self):
240
+ """Rereads the old contents of the cell back into the editing buffer.
241
+ Useful for a key binding when <Escape> is pressed to abort the edit
242
+ (a default binding)."""
243
+ self.tk.call(self._w, "reread")
244
+
245
+ def scan_mark(self, x, y):
246
+ self.tk.call(self._w, "scan", "mark", x, y)
247
+
248
+ def scan_dragto(self, x, y):
249
+ self.tk.call(self._w, "scan", "dragto", x, y)
250
+
251
+ def see(self, index):
252
+ self.tk.call(self._w, "see", index)
253
+
254
+ def selection_anchor(self, index):
255
+ self.tk.call(self._w, "selection", "anchor", index)
256
+
257
+ # pylint: disable=arguments-differ # TODO: maybe consider calling this method differently?
258
+ def selection_clear(self, first, last=None):
259
+ self.tk.call(self._w, "selection", "clear", first, last)
260
+
261
+ def selection_includes(self, index):
262
+ return self.getboolean(self.tk.call(self._w, "selection", "includes", index))
263
+
264
+ def selection_set(self, first, last=None):
265
+ self.tk.call(self._w, "selection", "set", first, last)
266
+
267
+ def set(self, *args, rc=None, index=None, **kwargs):
268
+ """If rc is specified (either 'row' or 'col') then it is assumes that
269
+ args (if given) represents values which will be set into the
270
+ subsequent columns (if row is specified) or rows (for col).
271
+ If index is not None and args is not given, then it will return the
272
+ value(s) for the cell(s) specified.
273
+
274
+ If kwargs is given, assumes that each key in kwargs is a index in this
275
+ table and sets the specified index to the associated value. Table
276
+ validation will not be triggered via this method.
277
+
278
+ Note that the table must have an associated array (defined through the
279
+ variable option) in order to this work."""
280
+ if not args and index is not None:
281
+ if rc:
282
+ args = (rc, index)
283
+ else:
284
+ args = (index,)
285
+ return self.tk.call(self._w, "set", *args)
286
+ if rc is None:
287
+ args = tkinter._flatten(list(kwargs.items()))
288
+ self.tk.call(self._w, "set", *args)
289
+ else:
290
+ self.tk.call(self._w, "set", rc, index, args)
291
+
292
+ def spans(self, index=None, **kwargs):
293
+ """Manipulate row/col spans.
294
+
295
+ When called with no arguments, all known spans are returned as a dict.
296
+ When called with only the index, the span for that index only is
297
+ returned, if any. Otherwise kwargs is assumed to contain keys/values
298
+ pairs used to set spans. A span starts at the row,col defined by a key
299
+ and continues for the specified number of rows,cols specified by
300
+ its value. A span of 0,0 unsets any span on that cell."""
301
+ if kwargs:
302
+ args = tkinter._flatten(list(kwargs.items()))
303
+ self.tk.call(self._w, "spans", *args)
304
+ else:
305
+ return self.tk.call(self._w, "spans", index)
306
+
307
+ def tag_cell(self, tagname, *args):
308
+ return self.tk.call(self._w, "tag", "cell", tagname, *args)
309
+
310
+ def tag_cget(self, tagname, option):
311
+ return self.tk.call(self._w, "tag", "cget", tagname, f"-{option}")
312
+
313
+ def tag_col(self, tagname, *args):
314
+ return self.tk.call(self._w, "tag", "col", tagname, *args)
315
+
316
+ def tag_configure(self, tagname, option=None, **kwargs):
317
+ """Query or modify options associated with the tag given by tagname.
318
+
319
+ If no option is specified, a dict describing all of the available
320
+ options for tagname is returned. If option is specified, then the
321
+ command returns a list describing the one named option. Lastly, if
322
+ kwargs is given then it corresponds to option-value pairs that should
323
+ be modified."""
324
+ if option is None and not kwargs:
325
+ split1 = self.tk.splitlist(self.tk.call(self._w, "tag", "configure", tagname))
326
+ result = {}
327
+ for item in split1:
328
+ res = self.tk.splitlist(item)
329
+ result[res[0]] = res[1:]
330
+ return result
331
+ if option:
332
+ return self.tk.call(self._w, "tag", "configure", tagname, f"-{option}")
333
+ args = ()
334
+ for key, val in kwargs.items():
335
+ args += (f"-{key}", val)
336
+ self.tk.call(self._w, "tag", "configure", tagname, *args)
337
+
338
+ def tag_delete(self, tagname):
339
+ self.tk.call(self._w, "tag", "delete", tagname)
340
+
341
+ def tag_exists(self, tagname):
342
+ return self.getboolean(self.tk.call(self._w, "tag", "exists", tagname))
343
+
344
+ def tag_includes(self, tagname, index):
345
+ return self.getboolean(self.tk.call(self._w, "tag", "includes", tagname, index))
346
+
347
+ def tag_lower(self, tagname, belowthis=None):
348
+ self.tk.call(self._w, "tag", "lower", tagname, belowthis)
349
+
350
+ def tag_names(self, pattern=None):
351
+ return self.tk.call(self._w, "tag", "names", pattern)
352
+
353
+ def tag_raise(self, tagname, abovethis=None):
354
+ self.tk.call(self._w, "tag", "raise", tagname, abovethis)
355
+
356
+ def tag_row(self, tagname, *args):
357
+ return self.tk.call(self._w, "tag", "row", tagname, *args)
358
+
359
+ def validate(self, index):
360
+ """Explicitly validates the specified index based on the current
361
+ callback set for the validatecommand option. Return 0 or 1 based on
362
+ whether the cell was validated."""
363
+ return self.tk.call(self._w, "validate", index)
364
+
365
+ @property
366
+ def version(self):
367
+ """Return tktable's package version."""
368
+ return self.tk.call(self._w, "version")
369
+
370
+ def width(self, column=None, **kwargs):
371
+ """If column and kwargs are not given, a dict describing all columns
372
+ for which a width has been set is returned.
373
+ If column is given, the width of that column is returned.
374
+ If kwargs is given, then it sets the key/value pairs, where key is a
375
+ column and value represents the width for the column."""
376
+ if column is None and not kwargs:
377
+ pairs = self.tk.splitlist(self.tk.call(self._w, "width"))
378
+ return dict(pair.split() for pair in pairs)
379
+ if column is not None:
380
+ return int(self.tk.call(self._w, "width", str(column)))
381
+ args = tkinter._flatten(list(kwargs.items()))
382
+ self.tk.call(self._w, "width", *args)
383
+
384
+ def window_cget(self, index, option):
385
+ return self.tk.call(self._w, "window", "cget", index, option)
386
+
387
+ def window_configure(self, index, option=None, **kwargs):
388
+ """Query or modify options associated with the embedded window given
389
+ by index. This should also be used to add a new embedded window into
390
+ the table.
391
+
392
+ If no option is specified, a dict describing all of the available
393
+ options for index is returned. If option is specified, then the
394
+ command returns a list describing the one named option. Lastly, if
395
+ kwargs is given then it corresponds to option-value pairs that should
396
+ be modified."""
397
+ if option is None and not kwargs:
398
+ return self.tk.call(self._w, "window", "configure", index)
399
+ if option:
400
+ return self.tk.call(self._w, "window", "configure", index, f"-{option}")
401
+ args = ()
402
+ for key, val in kwargs.items():
403
+ args += (f"-{key}", val)
404
+ self.tk.call(self._w, "window", "configure", index, *args)
405
+
406
+ def window_delete(self, *indexes):
407
+ self.tk.call(self._w, "window", "delete", *indexes)
408
+
409
+ def window_move(self, index_from, index_to):
410
+ self.tk.call(self._w, "window", "move", index_from, index_to)
411
+
412
+ def window_names(self, pattern=None):
413
+ return self.tk.call(self._w, "window", "names", pattern)
414
+
415
+ def xview(self, index=None):
416
+ """If index is not given a tuple containing two fractions is returned,
417
+ each fraction is between 0 and 1. Together they describe the
418
+ horizontal span that is visible in the window.
419
+
420
+ If index is given the view in the window is adjusted so that the
421
+ column given by index is displayed at the left edge of the window."""
422
+ res = self.tk.call(self._w, "xview", index)
423
+ if index is None:
424
+ return self._getdoubles(res)
425
+
426
+ def xview_moveto(self, fraction):
427
+ """Adjusts the view in the window so that fraction of the total width
428
+ of the table text is off-screen to the left. The fraction parameter
429
+ must be a fraction between 0 and 1."""
430
+ self.tk.call(self._w, "xview", "moveto", fraction)
431
+
432
+ def xview_scroll(self, *L):
433
+ # change by frank gao for attach scrollbar 11/11/2010
434
+ """Shift the view in the window left or right according to number and
435
+ what. The 'number' parameter must be an integer. The 'what' parameter
436
+ must be either units or pages or an abbreviation of one of these.
437
+
438
+ If 'what' is units, the view adjusts left or right by number cells on
439
+ the display; if it is pages then the view adjusts by number screenfuls.
440
+ If 'number' is negative then cells farther to the left become visible;
441
+ if it is positive then cells farther to the right become visible."""
442
+ # self.tk.call(self._w, 'xview', 'scroll', number, what)
443
+ op, howMany = L[0], L[1]
444
+ if op == "scroll":
445
+ units = L[2]
446
+ self.tk.call(self._w, "xview", "scroll", howMany, units)
447
+ elif op == "moveto":
448
+ self.tk.call(self._w, "xview", "moveto", howMany)
449
+
450
+ def yview(self, index=None):
451
+ """If index is not given a tuple containing two fractions is returned,
452
+ each fraction is between 0 and 1. The first element gives the position
453
+ of the table element at the top of the window, relative to the table
454
+ as a whole. The second element gives the position of the table element
455
+ just after the last one in the window, relative to the table as a
456
+ whole.
457
+
458
+ If index is given the view in the window is adjusted so that the
459
+ row given by index is displayed at the top of the window."""
460
+ res = self.tk.call(self._w, "yview", index)
461
+ if index is None:
462
+ return self._getdoubles(res)
463
+
464
+ def yview_moveto(self, fraction):
465
+ """Adjusts the view in the window so that the element given by
466
+ fraction appears at the top of the window. The fraction parameter
467
+ must be a fraction between 0 and 1."""
468
+ self.tk.call(self._w, "yview", "moveto", fraction)
469
+
470
+ def yview_scroll(self, *L):
471
+ # change by frank gao for attach scrollbar 11/11/2010
472
+ """Adjust the view in the window up or down according to number and
473
+ what. The 'number' parameter must be an integer. The 'what' parameter
474
+ must be either units or pages or an abbreviation of one of these.
475
+
476
+ If 'what' is units, the view adjusts up or down by number cells; if it
477
+ is pages then the view adjusts by number screenfuls.
478
+ If 'number' is negative then earlier elements become visible; if it
479
+ is positive then later elements become visible."""
480
+ # self.tk.call(self._w, 'yview', 'scroll', number, what)
481
+ op, howMany = L[0], L[1]
482
+ if op == "scroll":
483
+ units = L[2]
484
+ self.tk.call(self._w, "yview", "scroll", howMany, units)
485
+ elif op == "moveto":
486
+ self.tk.call(self._w, "yview", "moveto", howMany)
tktable/utils.py ADDED
@@ -0,0 +1,56 @@
1
+ # pylint: disable=protected-access
2
+
3
+ """Internal helpers shared by the modules of this package."""
4
+
5
+ import logging
6
+ import os
7
+ import tkinter
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+ #: Environment variable that can point to the directory containing Tktable's pkgIndex.tcl.
12
+ TKTABLE_LIBRARY_ENV_VAR = "TKTABLE_LIBRARY"
13
+
14
+
15
+ def _setup_master(master: tkinter.Misc | None) -> tkinter.Misc:
16
+ if master is None:
17
+ if tkinter._support_default_root: # type: ignore[attr-defined]
18
+ master = tkinter._default_root or tkinter.Tk() # type: ignore[attr-defined]
19
+ else:
20
+ raise RuntimeError(
21
+ "No master specified and Tkinter is configured to not support default master"
22
+ )
23
+ return master
24
+
25
+
26
+ def extend_auto_path(interp: tkinter.Misc) -> None:
27
+ """Append ``$TKTABLE_LIBRARY`` (if set) to Tcl's ``auto_path`` of ``interp``."""
28
+ library = os.environ.get(TKTABLE_LIBRARY_ENV_VAR)
29
+ if library:
30
+ logger.debug("Add %s to auto_path", library)
31
+ interp.tk.call("lappend", "auto_path", library)
32
+ else:
33
+ logger.debug("The environment variable %s is not defined.", TKTABLE_LIBRARY_ENV_VAR)
34
+
35
+
36
+ def find_tktable(interp: tkinter.Misc) -> list[str]:
37
+ """Return the versions of Tktable that Tcl can find, without loading it.
38
+
39
+ This does not need Tk (or a display), so it works in headless environments.
40
+ """
41
+ extend_auto_path(interp)
42
+ # Requiring a non-existent package makes Tcl scan auto_path for every pkgIndex.tcl.
43
+ interp.tk.eval("catch {package require __tktable_probe__}")
44
+ return [str(v) for v in interp.tk.splitlist(interp.tk.call("package", "versions", "Tktable"))]
45
+
46
+
47
+ def load_tktable(master: tkinter.Misc) -> str:
48
+ """Load the Tcl/Tk extension Tktable into the Tk interpreter of ``master``.
49
+
50
+ :return: the version of Tktable that was loaded.
51
+ :raise tkinter.TclError: if Tktable cannot be found or loaded.
52
+ """
53
+ extend_auto_path(master)
54
+ # https://wiki.tcl-lang.org/page/package+require
55
+ logger.debug("Require the Tcl/Tk extension Tktable.")
56
+ return str(master.tk.call("package", "require", "Tktable"))