gh-97928: Partially restore the behavior of tkinter.Text.count() by default (GH-115031)

By default, it preserves an inconsistent behavior of older Python
versions: packs the count into a 1-tuple if only one or none
options are specified (including 'update'), returns None instead of 0.
Except that setting wantobjects to 0 no longer affects the result.

Add a new parameter return_ints: specifying return_ints=True makes
Text.count() always returning the single count as an integer
instead of a 1-tuple or None.
This commit is contained in:
Serhiy Storchaka 2024-02-11 12:43:14 +02:00 committed by GitHub
parent 5d2794a16b
commit d2c4baa41f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 59 additions and 28 deletions

View file

@ -3745,7 +3745,7 @@ class Text(Widget, XView, YView):
return self.tk.getboolean(self.tk.call(
self._w, 'compare', index1, op, index2))
def count(self, index1, index2, *options): # new in Tk 8.5
def count(self, index1, index2, *options, return_ints=False): # new in Tk 8.5
"""Counts the number of relevant things between the two indices.
If INDEX1 is after INDEX2, the result will be a negative number
@ -3753,19 +3753,26 @@ class Text(Widget, XView, YView):
The actual items which are counted depends on the options given.
The result is a tuple of integers, one for the result of each
counting option given, if more than one option is specified,
otherwise it is an integer. Valid counting options are "chars",
"displaychars", "displayindices", "displaylines", "indices",
"lines", "xpixels" and "ypixels". The default value, if no
option is specified, is "indices". There is an additional possible
option "update", which if given then all subsequent options ensure
that any possible out of date information is recalculated."""
counting option given, if more than one option is specified or
return_ints is false (default), otherwise it is an integer.
Valid counting options are "chars", "displaychars",
"displayindices", "displaylines", "indices", "lines", "xpixels"
and "ypixels". The default value, if no option is specified, is
"indices". There is an additional possible option "update",
which if given then all subsequent options ensure that any
possible out of date information is recalculated.
"""
options = ['-%s' % arg for arg in options]
res = self.tk.call(self._w, 'count', *options, index1, index2)
if not isinstance(res, int):
res = self._getints(res)
if len(res) == 1:
res, = res
if not return_ints:
if not res:
res = None
elif len(options) <= 1:
res = (res,)
return res
def debug(self, boolean=None):