Reputation: 1603
I have text area in my Tkinter GUI. I want to implement an undo function which will delete the last line. For that, I need to get the line and column of the last line.
How do I get the line and position of the last line? And once I get the positions, how do I delete the line?
I have searched for this on google, but I am not getting any worthwhile links.
Upvotes: 4
Views: 11942
Reputation: 385900
The index of the last line is "end"
or the tkinter constant END
. tkinter always inserts an invisible newline at the end, so this actually represents the index immediately after the last character entered by the user.
You can get the line and column number by using the index
method of the text widget. So, for example, to get the row/column of the last character with this:
pos = textwidget.index("end")
You can add modifiers to an index, to get a position relative to another position. For example, to get the index of the start of the line you can append linestart
(eg: "3.5 linestart" will give you 3.0). You can also subtract characters by appending "-n chars" or "-nc" (eg: "3.5-1c" will give you 3.4).
These modifiers can be combined. So, in the case of wanting to find the start of the last line of text you want to go from the end (which is actually after the extra newline that tkinter adds), back up one character to get to the end of the line, then use "linestart" to get to the beginning:
pos = textwidget.index("end-1c linestart")
For what it's worth, this is all documented and pretty easy to find. At the time that I write this, the first result when I search google for "tkinter text widget" points to a page which documents the text widget index expressions: http://effbot.org/tkinterbook/text.htm. Look for the section named "expressions".
To delete a line of text, you need to call the delete
method with the starting and ending index of the text you want to delete. To delete the last line, use this:
textwidget.delete("end-1c linestart", "end")
Upvotes: 19