How to create a hyperlink with a Label in Tkinter?
Asked Answered
T

8

29

How do you create a hyperlink using a Label in Tkinter?

A quick search did not reveal how to do this. Instead there were only solutions to create a hyperlink in a Text widget.

Twentieth answered 5/5, 2014 at 22:10 Comment(1)
It is a shopping question, not a creative problem. Consult official documentation or forum.Prestige
T
57

Bind the label to "<Button-1>" event. When it is raised the callback is executed resulting in a new page opening in your default browser.

from tkinter import *
import webbrowser

def callback(url):
    webbrowser.open_new(url)

root = Tk()
link1 = Label(root, text="Hyperlink", fg="blue", cursor="hand2")
link1.pack()
link1.bind("<Button-1>", lambda e: callback("http://www.example.com"))

link2 = Label(root, text="Hyperlink", fg="blue", cursor="hand2")
link2.pack()
link2.bind("<Button-1>", lambda e: callback("http://www.example.org"))

root.mainloop()

You can also open files by changing the callback to:

webbrowser.open_new(r"file://c:\test\test.csv")
Twentieth answered 5/5, 2014 at 22:10 Comment(5)
+ Peregrinius What does the 'r' in the open_new argument do?Baize
It makes the string literal. So you don't have to escape the backslashes.Twentieth
@JamesBurke how can you apply this solution if you have two labels you would like to make links?Germann
maybe I'm nitpicking but the more tkinter's way it's to bind() function to label before pack() it.Paramatta
Wouldn't it be better to bind to "<ButtonRelease-1>"?Teresetereshkova
S
12

Alternatively if you have multiple labels and want the one function for all. That is assuming you have the link as the text

import tkinter as tk
import webbrowser

def callback(event):
    webbrowser.open_new(event.widget.cget("text"))

root = tk.Tk()
lbl = tk.Label(root, text=r"http://www.example.com", fg="blue", cursor="hand2")
lbl.pack()
lbl.bind("<Button-1>", callback)
root.mainloop()
Sublittoral answered 7/10, 2015 at 6:33 Comment(1)
Wouldn't it be better to bind to "<ButtonRelease-1>"?Teresetereshkova
C
4

There is a module on PyPi called tkhtmlview (pip install tkhtmlview) that supports HTML in tkinter. It only supports some tags, but on the page, it says that it has full support fro tags (anchor tags for hyperlinks), and supports the href attribute. It requires Python 3.4 or later with tcl/tk (tkinter) support and the Pillow 5.3.0 module. I haven't tried the tag yet, but I tried the module in general and it works.

As an example:

import tkinter as tk
from tkhtmlview import HTMLLabel

root = tk.Tk()
html_label=HTMLLabel(root, html='<a href="http://www.example.com"> Hyperlink </a>')
html_label.pack()
root.mainloop()
Carnap answered 16/3, 2020 at 3:23 Comment(0)
I
1

You can simply import webbrowser, add a function and call that inside of the button. Declare your layout manager. Here is how the code looks like:

from tkinter import *
import webbrowser

# Displaying the root window
window = Tk()
window.config(padx=100, pady=100)


# Function Declaration
def callback():
    webbrowser.open_new("https://www.example.com/")


# Button Declaration
your_variable_name = Button(text="button_name", command=callback)
your_variable_name.grid(column=2, row=3)

# keeping the Tkinter Interface running
window.mainloop()

FYI. It'll open in computer's default browser

Idler answered 8/7, 2021 at 18:13 Comment(0)
B
0

you can create a class that inherits from label widget of tkinter module , initialize it with additional values including the link of course ... then you create an instance of it as shown below.

import tkinter as t
import webbrowser


class Link(t.Label):
    
    def __init__(self, master=None, link=None, fg='grey', font=('Arial', 10), *args, **kwargs):
        super().__init__(master, *args, **kwargs)
        self.master = master
        self.default_color = fg # keeping track of the default color 
        self.color = 'blue'   # the color of the link after hovering over it 
        self.default_font = font    # keeping track of the default font
        self.link = link 

        """ setting the fonts as assigned by the user or by the init function  """
        self['fg'] = fg
        self['font'] = font 

        """ Assigning the events to private functions of the class """

        self.bind('<Enter>', self._mouse_on)    # hovering over 
        self.bind('<Leave>', self._mouse_out)   # away from the link
        self.bind('<Button-1>', self._callback) # clicking the link

    def _mouse_on(self, *args):
        """ 
            if mouse on the link then we must give it the blue color and an 
            underline font to look like a normal link
        """
        self['fg'] = self.color
        self['font'] = self.default_font + ('underline', )

    def _mouse_out(self, *args):
        """ 
            if mouse goes away from our link we must reassign 
            the default color and font we kept track of   
        """
        self['fg'] = self.default_color
        self['font'] = self.default_font

    def _callback(self, *args):
        webbrowser.open_new(self.link)  


root = t.Tk()
root.title('Tkinter Links !')
root.geometry('300x200')
root.configure(background='LightBlue')

URL = 'www.example.org'

link = Link(root, URL, font=('sans-serif', 20), text='Python', bg='LightBlue')
link.pack(pady=50)

root.mainloop()
Bellabelladonna answered 29/10, 2020 at 22:22 Comment(0)
C
0
""" Hyperlink *with* hover affect - Wallee """

from tkinter import *
import webbrowser


# Creates hyperlinks
def hyperlink(root, link: str, **kwargs) -> Label:

    # Iterate through a few default settings to make it look like a link
    for i in (("fg", "blue"), ("text", "Hyperlink!"), ("font", "None 10"), ("cursor", "hand2")):
        kwargs.setdefault(i[0], i[1])

    # Create the label
    label = Label(root, **kwargs)
    label.link = link

    # Bind the click event to a lambda that opens the link using the webbrowser module
    label.bind("<Button-1>", lambda e: webbrowser.open(e.widget.link))

    # Bind the enter and leave events to add a hover affect
    label.bind("<Enter>", lambda e: e.widget.configure(font=e.widget.cget("font") + " underline"))
    label.bind("<Leave>", lambda e: e.widget.configure(font=e.widget.cget("font")[:-10]))

    return label

# Basic Tkinter setup
root = Tk()
root.geometry("150x50")

# Create and pack the "hyperlink" (AKA label)
link = hyperlink(root, "https://www.example.com", font="None 15")
link.pack()

root.mainloop()
Conformation answered 13/1, 2023 at 5:10 Comment(0)
K
0
from tkinter import *
import tkinter as tkr
import webbrowser


link = Label(root, text="Forgot your password?", fg="blue", cursor="hand2")
link.grid(row=4,column=3)
link.bind("<Button-1>", lambda e: webbrowser.open_new_tab("https://example.com/?forget_password")

)
Klatt answered 21/7, 2023 at 9:30 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Peery
P
0

To create a link type you need to bind a button with a label:

from tkinter import *
import webbrowser

def callback(link):
    webbrowser.open_new(link)

root = Tk()
link = Label(root, text="Click to visit website", cursor="hand")
link.bind("<Button-1>", callback("http://www.example.com"))
link.pack()
root.mainloop()

We used a callback function to open the website and then called it when our link is clicked.

Make sure to call the link.pack() function after we bind the label.

Plain answered 12/12, 2023 at 19:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.