[Tkinter-discuss] How can I edit a string inside a textbox?

Fredrik Lundh fredrik at pythonware.com
Thu Dec 6 12:27:17 CET 2007

Alex Garipidis wrote:

> I have a Tkinter Textbox in my application. I want to scan the
 > textbox for a symbol, defined by me as a "mark", and
 > change the word that is inside or next to that symbol.
> This is what i mean:
> If a user types this to the textbox:
> "Hello @everybody, how are you doing?"
> I want to scan this string for the "@" character (or something
 > else) and edit the word next to it (or "inside" it, e.g.
 > "@everybody@"), "everybody" in this case, and make it have
 > a color for example or make it underlined.

to find things in a text widget, use the "search" method:

    pos = text.search(string, start)

where "string" is the string you want to search for, and start is the 
starting position (e.g. 1.0 or INSERT).

to search for things that match "@word", where "word" is an arbitrary 
string of letters or digits, you can use a regular expression, e.g.

    pos = text.search("@\w+", 1.0, regexp=True)

search only returns where the match begins; to find the end of "@word", 
you can search from the given position to the first thing that isn't a 
word character:

    end = text.search("\W", pos + " 1 char", regexp=True)

to change the appearance of a block of text, register the style using 
tag_config, and then use tag_add to apply the style tag to the block, e.g.:

    # do this when you create the widget
    text.tag_config("mystyle", foreground="red")

    # do this to apply this style to a range of text
    text.tag_add("mystyle", pos, end)

hope this helps!


More information about the Tkinter-discuss mailing list