How do you create a clickable Tkinter Label?

TkinterPythonGUI-Programming

Label widgets in Tkinter are used to display text and images. We can link a URL with the label widget to make it clickable. Whenever the label widget is clicked, it will open the attached link in the default browser.

To work with the browser and hyperlinks we can use webbrowser module in Python. The module is accessible in Python extension library and can be installed by typing the command pip install webbrowser in the shell.

Example

In this application, we will create a Label which turns out to be a Hyperlink referring to a webpage.

# Import the required library
from tkinter import *
import webbrowser

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

def open_url(url):
   webbrowser.open_new_tab(url)

# Create a Label Widget
label= Label(win, text= "Welcome to TutorialsPoint", cursor= "hand2", foreground= "green", font= ('Aerial 18'))
label.pack(pady= 30)

# Define the URL to open
url= 'https://www.tutorialspoint.com/'

# Bind the label with the URL to open in a new tab
label.bind("<Button-1>", lambda e:open_url(url))
win.mainloop()

Output

Upon clicking the label, the user will be redirected to the homepage of Tutorialspoint.

raja
Published on 07-Jun-2021 11:05:30
Advertisements