How to create clickable link with Tkinter in Python with Label
In this tutorial, we will learn how to create clickable link with custom label in Python with Tkinter.
To achieve this task we are using the tkinter
library for creating GUIs and webbrowser
module for opening URLs.
Step 1: Importing required libraries
import tkinter as tk import webbrowser
Step 2: Creating a GUI window using tkinter
window = tk.Tk() window.title("Clickable Links")
window.title()
: this accepts a text that will be displayed on the title of GUI Window
Step 3: Defining functions and creating labels
def open_link(): webbrowser.open_new("https://www.codespeedy.com/") #Link which will open when you click label label = tk.Label(window, text="CodeSpeedy", fg="blue", cursor="hand2")
webbrowser.open_new()
: This acceptsurl
as a parameter and open the link in the browser.- text: This is your label which will be displayed instead of URL.
- fg: This is the text color of your label.
- cursor: This is an optional parameter, this will change your cursor icon when you hover over the text.
Step 4: Bind function with label and pack into GUI window
label.bind("<Button-1>", lambda e: open_link()) label.pack()
- here we are using
lambda
function because if we directly passopen_link()
function, it will automatically run this function without even clicking on the label.
Step 5: Run the GUI
window.mainloop()
Output
We’ve successfully learned to create clickable link with Custom label in Python. I hope you found this tutorial informative!
Leave a Reply