1

I'm having trouble capturing a Tkinter Text's widgets first line of code.

Under two conditions, with and without a newline char inputted into the input text widgets field.

Further more

  • I'd like to capture the second line of code
  • then the third line.

I don't mean, line up to a newline char.
I mean a line, as in the line with length = width of the text widget in chars.

Passing floats and strings as arguments and literals to test simple cases that are less generic and durable.

inputText = self.windowIn.get(1.0, 2.0)

This grabs everything up to the end of the inputted line (meaning up to the first newline char).

stovfl
  • 14,998
  • 7
  • 24
  • 51

1 Answers1

1

If you want to get a specific number of characters you can use a modifier on an index. For example, to get the first 30 characters of line 1, you can use something like self.windowIn.get('1.0', '1.0+30c')

The text widget also has the concept of a "display line". A display line represents what you see, taking into consideration wrapping done by the widget. If you have a line that is 60 characters wide and the text is wrapped at 30 characters, you can use the display submodifier to get all of the characters on a displayed line rather than the full line.

For example, consider a widget that looks like this, with a single line that wraps at 30 characters (ie: no newlines in the data):

123456789012345678901234567890
123456789012345678901234567890
123456789012345678901234567890

The index 1.0 display lineend is the same as 1.29, since that's the index of the 30th character.

When you give a second index to the get method, it returns all characters up to that index, but not including the character at that index. Thus, when getting a display line you need to add one character to the end index to capture that last character.

So, putting that all together, you can get all of the text on the first displayed line with this:

self.windowIn.get("1.0", "1.0 display lineend +1c").

For the canonical description of text widget indexes, see the official tcl/tk documentation here: http://tcl.tk/man/tcl8.5/TkCmd/text.htm#M7

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685