Welcome folks today in this blog post we will be opening external hyperlinks or youtube videos in web browser using the tkinter library. All the full source code of the application is shown below.
Get Started
In order to get started guys you need to create the app.py
file inside the root directory and copy paste the below code as shown below
app.py
1 2 3 4 5 6 7 8 |
import webbrowser from tkinter import * window = Tk() window.title("Open Hyperlinks in Browser") window.geometry("300x100") window.mainloop() |
Setting the Dimensions of Tkinter Window
As you can see in the above code we are importing the tkinter library and then initializing a new instance of the tkinter library. And then using that object we are setting the title of the app and also setting the geometry of the window passing the width and height of the window. And then we are using the mainloop() method to start the tkinter app. This will show the below window
1 2 3 4 5 |
label = Label(text="Open Hyperlinks in Browser") label.pack() labelOne = Label(text="Open Youtube Videos Also") labelOne.pack() |
Displaying the Labels Widget
As you can see we are displaying the two labels widget on the screen and simply adding them to the screen using the pack() method of tkinter.
1 2 3 4 5 6 7 8 |
url = "https://www.google.com" video_url="https://www.youtube.com/watch?v=DxMPnNAbhRc" click = Button(text="Go to Google", command=lambda: onClick(url)) video_widget = Button(text="Go to Video", command=lambda: onClick(video_url)) click.pack() video_widget.pack() |
Displaying the Buttons Widget
As you can see we are displaying the two buttons which is used for opening the website hyperlink and also the video as well inside the browser. And inside the button we have the command property which has lambda attribute and then we are defining the onClick method which will be triggered when the button is clicked.
And now we will be defining this method which will be taking the url to open inside the browser. The method is shown below
1 2 |
def onClick(x): webbrowser.open(x,new=1) |
As you can see we are using the open()
method to open the url inside the web browser. And also we are providing the second argument which is equal to 1. This helps us to open the url inside the new browser tab.
Full Source Code
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import webbrowser from tkinter import * window = Tk() window.title("Open Hyperlinks in Browser") window.geometry("300x100") def onClick(x): webbrowser.open(x,new=1) label = Label(text="Open Hyperlinks in Browser") label.pack() labelOne = Label(text="Open Youtube Videos Also") labelOne.pack() url = "https://www.google.com" video_url="https://www.youtube.com/watch?v=DxMPnNAbhRc" click = Button(text="Go to Google", command=lambda: onClick(url)) video_widget = Button(text="Go to Video", command=lambda: onClick(video_url)) click.pack() video_widget.pack() window.mainloop() |