简体   繁体   中英

tkinter: getting index of selected text in textbox from 1st char

How do I get the position of selected text from the 1st character in the string. When I do

 ind = textwidget.index("self.first")

I only get index as line.column. What I would like to have is the number of characters from the start of the first character. The motivation for doing this way is that I do not have to bother the way formatting is done in the UI which results in number of lines (together with newline chars in string).

Is it possible ?

The text widget has a method named count which will give you the count of the number of characters between two positions. This method is available with python3, but not with python2. However, there's a simple fix for python2.

For python3, to get the count of characters between the start of the widget and the first selected character you could do something like this:

count = textwidget.count("1.0", "sel.first")

For python2, you have to call the underlying tcl interpreter since the method isn't exposed by the text widget. Assuming your root widget is named root , you would do it like this:

count = root.call(textwidget, "count", "1.0", "sel.first")

The count method takes many options. For example, you can count the number of pixels, you can include or exclude hidden lines, etc. For the definitive list of options supported by the underlying tcl/tk engine, see http://tcl.tk/man/tcl8.5/TkCmd/text.htm#M72

I presume by 'first character' you mean the first character in the text, at index '1.0', since otherwise the index column would be your answer. If so, then you will have to sum the number of characters in previous lines and add the column from the index.

import tkinter as tk
root = tk.Tk()
t = tk.Text(root)
t.insert('1.0', 'abcxyz\n')
t.insert('2.0', 'def\n')
t.insert('3.0', 'ghik\n')
# line, column = map(int, t.index('sel.first').split('.'))
line, column = 3, 2  # simulate 'i' beginning selection
column += sum(int(t.index('%d.end' % i).split('.')[1])
              for i in range(1, line))
column += (line - 1)  # to count \n's
print(column)

prints 13, as expected. You can also get the previous text and let python sum the lengths. This also prints 13 if inserted right after line, column = ... .

s = t.get('1.0', '%d.%d' % (line, column))
print(s, len(s))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM