Swapping lines in a Tkinter text widget

I Have everything set up, I just can’t figure out how to swap 2 lines in a Tkinter text widget. It’s disabled and populated by other widgets so I gave the disabled/unfocused text widget some functionality with 3 buttons; Move_Up, Move_Down, and Delete. I have delete working but can’t figure out how to get the other two to work. Right now i’m working with 2 values that reference the start and end of the line of text that is going to be modified: self.line_start and self.line_end

And here’s what I have so far:

def Move_Up(self):
   #swap this line with the line above it

def Move_Down(self):
   #swap this line with the line below it

def Delete(self):
   #delete the line
   #delete the carriage return

Basically, how would I implement my values of self.line_start and self.line_end to swap the line with the line before it or the line after it.


You can get the index of any position in the widget with the index method. You can give it an argument that includes modifiers such as linestart and lineend. You can also get the index of a relative position with something like +1c to get the index of the next character, or +1l to get the next line. You can also use wordstart and wordend. You can combine them, for example: index("insert lineend +1c")

For example, to get the start and end of the line that has the insertion cursor (where ‘insert’ is the name of the mark that represents the insertion cursor):

start = self.TextWidg("insert linestart")
end = self.TextWidg("insert lineend")

For more information, see the section titled “expressions” on the text widget page on effbot.org.

Leave a Reply

Your email address will not be published. Required fields are marked *