Marking hyperlinks in a Text widget

Cliff Crawford cjc26 at nospam.cornell.edu
Wed May 31 00:12:51 EDT 2000


* André Dahlqvist <andre at beta.telenordia.se> menulis:
| 
| Thanks for the suggestion, but this is not really what I am looking for. 
| I just need to find strings in a Text widget that starts with http:// or 
| ftp:// and change the color of them to blue and underlined. I tried 
| checking the IDLE source since the IDLE editor does color markup, but
| it was too complex to figure out how to translate this into my little
| problem. Does anyone have any other suggestions?

Here's what I do in my irc client:

textw.tag_config('url', foreground='blue', underline=1)
textw.tag_bind('url', '<Enter>', show_hand_cursor)
textw.tag_bind('url', '<Leave>', show_arrow_cursor)
textw.tag_bind('url', '<Button-1>', click)

urlfinder=re.compile(r'((?:http://|www\.)[^\s<>[\]{}()`"\'|\\^$]+[^\s<>[\]{}()`"
\'|\\^$.?!:;\-])')

l=urlfinder.split(str)
for n in range(len(l)):
    if n%2 == 1:
        textw.insert('end', l[n], ('url', l[n]))
                            # use a tuple so url can be retrieved later
    else:
        textw.insert('end', l[n])

def click(event):
    os.system("netscape -remote 'openURL(%s)'" % \
               textw.tag_names('@%d,%d' % (event.x, event.y))[1])


Basically I'm using re.split to split the text into a list of
alternating urls and non-urls.  Then, I insert every other member of the
list (the urls) with the url tag.  The click() function shows how you
can retrieve the url later.  (It took me a while to figure that one out,
so I figured I'd be nice and show you that too. ;)


-- 
cliff crawford    -><-    http://www.people.cornell.edu/pages/cjc26/
                          Synaesthesia now!            icq 68165166



More information about the Python-list mailing list