Open sites with Python and webbrowser

Hello, I revisited a post I made last year to add some ‘features’ to that very simple script to open chrome with python and the module webbrowser.

I decided to add a little GUI to choose among some defined links as you can intuitively understand watching the following window:

The code is the following:

import tkinter as tk
import webbrowser

class Check:
	def __init__(self, master, site):
		"""Creates checkbuttons to choose sites"""
		self.var = tk.IntVar()
		self.site = site
		self = tk.Checkbutton(
			master,
			text = self.site,
			variable = self.var,
			command=self.print_info
			).pack()

	def print_info(self):
		print(f"site: {self.site}\n {self.var.get()}")
		if self.var.get() == 1:
			checked.append(self.site)
		else:
			checked.remove(self.site)

class App:
	def __init__(self, sites):
		"""Creates window with checkbuttons"""
		c = []
		master = tk.Tk()
		for s in sites:
			c.append(Check(master, s))
		tk.Button(master, text="Launch Chrome", command = lambda: self.start()).pack()
		master.mainloop()

	def start(self):
		"""Opens the browser with checked sites"""
		chrome = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s" 
		w = webbrowser.get(chrome)
		for site in checked:
			w.open(site)

checked = []
app = App(["www.google.com",
           "www.gmail.com",
           "https:\\pythonprogramming.altervista.org"])

While the video of the live coding will be ready, you can go and check the original post for more information about the process that brought me to this final code.

Go to read the original post clicking this link

Opening web pages without tkinter

With the following code we can open the windows, but just with the console, without using tkinter.

import tkinter as tk
import webbrowser


sites = ["https://pythonprogramming.altervista.org/wp-admin/post.php?post=122&action=edit",
        "https://pythonprogramming.altervista.org/wp-admin",
        "https://aziendaitalia.altervista.org/wp-admin"]

for n, s in enumerate(sites):
    print(n,s)

print("Write the number of the site you wanto to open, separated by a space")
checked = input("Wich site you want to open?")
checked = [sites[int(f)] for f in checked.split(" ")]


def openweb():
    chromedir= 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
    for site in checked:
        webbrowser.get(chromedir).open(site)

openweb()

Next thing we could do is to add the chance to add a new site or to delete the ones that are already in the list.

Add new sites to tkinter app

Ok, now it’s time to make this app more “user friendly”. Let’s add the chance to add sites to the ones that we put in the code with:

sites = ["https://pythonprogramming.altervista.org/wp-admin/post.php?post=122&action=edit",
        "https://pythonprogramming.altervista.org/wp-admin",
        "https://aziendaitalia.altervista.org/wp-admin"]

We could add them into this script, but we want to do it from the GUI.

Let’s make it following these steps:

Here the user will digit the address he wants to add:

    l = tk.Label(master, text="Add a new site").pack()
    e = tk.Entry(master)
    e.pack()

and when he hits return the widget will appear with the link. We use the bind method to make a function call (addsite) when an action is performed into the widget: the action is the key press of the Return (enter) button. So: the user write the address and then press Return and the checkbutton will appear.

    e.bind("<Return>", addsite)

Now we need to add the addsite function

def addsite(event):
    global c,e,master
    sites.append(e.get())
    c.append(Check(master, e.get()))
    with open("links.txt", "a") as file:
        file.write(e.get() + "\n")

When Return is pressed, we create the Checkbutton with the class Check, passing the master and the value in the entry with e.get(). Then we write this address into the links.txt, so that you will have it saved for the next time you use the app. You need to have a file named links.txt in the folder of the script (next time we will let the code do check if the file exists).

At the end of selected we add this loop, so that when the app runs it will load the new sites at the end of the default three ones.

with open("links.txt") as file:
    for line in file:
        sites.append(line)

P.S.: you can put all your sites in links.txt, you can manually add the sites in links.txt or delete the ones you don’t want anymore or even delete all of them.

Next time we will add a way to delete the address from the GUI of the app.

Let’s take a look at the code to open web pages with tkinter

# Original post:
"""
Open Chrome with Python and webbrowser
""" import tkinter as tk import webbrowser def openweb(browser=""): if browser == "chrome": chromedir= 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s' for site in checked: webbrowser.get(chromedir).open(site) class Check: def __init__(self, master, site): self.var = tk.IntVar() self.site = site self = tk.Checkbutton( master, text=self.site, variable=self.var, command=self.print_info).pack() def print_info(self): print(f"status of {self.site}: {self.var.get()}") if self.var.get() == 1: checked.append(self.site) else: checked.remove(self.site) def addsite(event): global c,e,master sites.append(e.get()) c.append(Check(master, e.get())) with open("links.txt", "a") as file: file.write(e.get() + "\n") sites = ["https://pythonprogramming.altervista.org/wp-admin/post.php?post=122&action=edit", "https://pythonprogramming.altervista.org/wp-admin", "https://aziendaitalia.altervista.org/wp-admin"] with open("links.txt") as file: for line in file: sites.append(line) checked = [] def start(): global c,e,master c = [] master = tk.Tk() for s in sites: c.append(Check(master, s)) tk.Button(master, text="Launch browser", command = lambda: openweb("chrome")).pack() l = tk.Label(master, text="Add a new site").pack() e = tk.Entry(master) e.pack() e.bind("<Return>", addsite) master = tk.mainloop() start()

This is an example of the window

tkinter app webbrowser

This is the link.txt content after adding the 2 sites you see in the image above:

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.