How to create hyperlink in a Tkinter Text widget?


Tkinter Text widgets are generally used for accepting multiline user input in the given text field. For a particular text document, the content may contain hyperlinks too which is useful in case we want to redirect the user. You can create hyperlinks within the text widget by using HyperLinkManager snippet in Python.

The HyperLinkManager code snippet adds the hyperlink on the keyword within the text widget. You can download the HyperLinkManager Snippet from here−

https://github.com/codewithdev/Code-Snippets/blob/master/tkinter/tkHyperlinkManager.py/

Once the snippet has been downloaded, you can import it in the notebook by typing "from tkHyperLinkManager import HyperlinkManager"

Example

# Import the required libraries
from tkinter import *
from tkHyperLinkManager import HyperlinkManager
import webbrowser
from functools import partial

# Create an instance of tkinter frame
win = Tk()
win.geometry("700x350")

# Define a callback function
def callback(url):
   webbrowser.open_new_tab(url)

# Create a Label to display the link
text = Text(win)
text.insert(END,"Hey Folks, Welcome to ")
text.pack()
hyperlink= HyperlinkManager(text)

text.insert(END,
"TutorialsPoint",hyperlink.add(partial(webbrowser.open,"http://www.tutorialspoint.com")))

win.mainloop()

Output

Executing the above code snippet will display a window containing a text widget and a keyword with hyperlink.

Whenever we click the link, it will open the URL on a web browser.

Updated on: 07-Jun-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements