Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

tkinter

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 ?

like image 365
Captain Jack sparrow Avatar asked Oct 28 '25 08:10

Captain Jack sparrow


1 Answers

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

like image 168
Bryan Oakley Avatar answered Oct 31 '25 03:10

Bryan Oakley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!