Tkinter indexing words issue Tkinter indexing words issue tkinter tkinter

Tkinter indexing words issue


You can't modify how "wordstart" defines "words". From the official documentation:

?submodifier? wordstart - Adjust the index to refer to the first character of the word containing the current index. A word consists of any number of adjacent characters that are letters, digits, or underscores, or a single character that is not one of these. If the display submodifier is given, this only examines non-elided characters, otherwise all characters (elided or not) are examined.

You can use the built-in search feature of the text widget to find the start and end of the word for however you want to define "word". You can search for regular expressions, so you can search for a pattern like [-\w] to get either a dash or a word character.

Off the top of my head, it might look something like this:

def userOptions(event):    count = IntVar()    pattern = r'[-\w]+'    # find the beginning of the "word", starting _after_    # the character clicked on    start = "@%d,%d +1c" % (event.x, event.y)    index1 = text.search(pattern, start, backwards=True, regexp=True)    # starting with the beginning, find the end and save    # the number of characters that matched.    text.search(pattern, index1, regexp=True, count=count)    # compute the ending index of the match    index2=text.index("%s + %s c" % (index1, count.get()))    # get the text    user = text.get(index1, index2)    print user    return

By the way, your code will be much easier to understand and maintain if you avoid the use of lambda except when absolutely necessary, and it's definitely not necessary in this case. Using the above code, you can simplify the binding to this:

text.tag_bind("click", "<Button-1>", userOptions)