Search code examples
pythonpython-2.7tkintertext-widget

Moving to a specific position in a text widget tkinter


i wanted to know if it's possible to move to a specific position in a text widget in tkinter. I implemented search in text widget and wanted to implement "next" and "previous" methods for my search to move across the text widget. Is it possible to do? Thanks for any help.

Here is a code for my method:

def find():
    xml.tag_delete("search")
    xml.tag_configure("search", background="green")
    start="1.0"
    if len(fi.get()) > 0:
        xml.mark_set("insert", xml.search(fi.get(), start))
        while True:
            pos = xml.search(fi.get(), start, END) 
            if pos == "": 
                break       
            start = pos + "+%dc" % len(fi.get()) 
            xml.tag_add("search", pos, "%s + %dc" % (pos,len(fi.get())))

fi is an entry field for search pattern. xml is a text field.


Solution

  • The text widget has marks, which are in effect named positions. The insertion cursor is defined by the mark "insert" (and the tkinter constant INSERT). You can move this index using the mark_set method.

    For example, this moves the insertion cursor to line 3, character 14:

    the_widget.mark_set("insert", "3.14")
    

    If you want to make sure the new insert position is visible you can use the see method, which will scroll the widget enough for the given index to be visible:

    the_widget.see("insert")