How it works...

First, we will initialize the tag by configuring the color and underline style. We add event bindings to open the clicked text with a browser and to change the cursor appearance while placing the mouse over the tagged text:

def __init__(self):
# ...
self.text.tag_config("link", foreground="blue", underline=1)
self.text.tag_bind("link", "<Button-1>", self.open_link)
self.text.tag_bind("link", "<Enter>",
lambda e: self.text.config(cursor="hand2"))
self.text.tag_bind("link", "<Leave>",
lambda e: self.text.config(cursor=""))

Within the open_link method, we transform the clicked position to the corresponding line and column using the index method of the Text class:

position = "@{},{} + 1c".format(event.x, event.y)
index = self.text.index(position)
prevrange = self.text.tag_prevrange("link", index)

Note that the position corresponding to the clicked index is "@x,y", but we moved it to the next character. We do this because tag_prevrange returns the preceding range to the given index, so it will not return the current range if we click on the first character.

Finally, we will retrieve the text from the range and open it with the default browser using the open function from the webbrowser module:

url = self.text.get(*prevrange)
webbrowser.open(url)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset