Programmatically opening URLs in a web browser in Python (tkinter)

Python provides a webbrowser module that allows you to programmatically open URLs in web browsers. This module is part of Python's standard library and creates an interface to display web-based content directly from your applications.

Installing the Webbrowser Module

The webbrowser module comes pre-installed with Python, so you can import it directly ?

import webbrowser

If for some reason the module is not available, you can install it using pip ?

pip install webbrowser

Opening URLs in Default Browser

The open() function opens a URL in the default web browser ?

import webbrowser

# Open URL in default browser
url = 'https://www.tutorialspoint.com/'
webbrowser.open(url)

Opening URLs in New Tab

Use open_new_tab() to force opening the URL in a new browser tab ?

import webbrowser

# Open URL in a new tab
url = 'https://www.tutorialspoint.com/'
webbrowser.open_new_tab(url)

Opening URLs in New Window

Use open_new() to open the URL in a new browser window ?

import webbrowser

# Open URL in a new window
url = 'https://www.tutorialspoint.com/'
webbrowser.open_new(url)

Specifying Browser Type

You can specify which browser to use by getting a browser controller ?

import webbrowser

url = 'https://www.tutorialspoint.com/'

# Try to open in Chrome
try:
    chrome = webbrowser.get('chrome')
    chrome.open(url)
except webbrowser.Error:
    print("Chrome browser not found, using default")
    webbrowser.open(url)

Common Browser Names

Browser Name Platform
Chrome 'chrome' Windows/Linux
Firefox 'firefox' All
Safari 'safari' macOS
Edge 'windows-default' Windows

Tkinter Integration Example

Here's how to integrate webbrowser with a tkinter GUI application ?

import tkinter as tk
import webbrowser

def open_website():
    url = entry.get()
    if url:
        webbrowser.open(url)
    else:
        webbrowser.open('https://www.tutorialspoint.com/')

root = tk.Tk()
root.title("URL Opener")
root.geometry("400x150")

tk.Label(root, text="Enter URL:").pack(pady=10)
entry = tk.Entry(root, width=50)
entry.pack(pady=5)

button = tk.Button(root, text="Open in Browser", command=open_website)
button.pack(pady=10)

root.mainloop()

Conclusion

The webbrowser module provides simple methods to open URLs programmatically. Use open() for basic functionality, open_new_tab() for new tabs, and get() to specify particular browsers for enhanced control.

---
Updated on: 2026-03-25T22:27:49+05:30

810 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements