{"id":2803,"date":"2019-08-10T08:31:27","date_gmt":"2019-08-10T06:31:27","guid":{"rendered":"https:\/\/pythonprogramming.altervista.org\/?p=2803"},"modified":"2019-08-11T11:04:04","modified_gmt":"2019-08-11T09:04:04","slug":"open-sites-with-python-and-webbrowser","status":"publish","type":"post","link":"https:\/\/pythonprogramming.altervista.org\/open-sites-with-python-and-webbrowser\/","title":{"rendered":"Open sites with Python and webbrowser"},"content":{"rendered":"<p><a href=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/08\/chrome2.png\"><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-2808 aligncenter\" src=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/08\/chrome2.png\" alt=\"\" width=\"201\" height=\"137\" \/><\/a><\/p>\n<p>Hello, I revisited a post I made last year to add some &#8216;features&#8217; to that very simple script to open chrome with python and the module webbrowser.<\/p>\n<p>I decided to add a little GUI to choose among some defined links as you can intuitively understand watching the following window:<\/p>\n<p><a href=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2018\/04\/chrometk.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-2801\" src=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2018\/04\/chrometk.png\" alt=\"\" width=\"490\" height=\"133\" srcset=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2018\/04\/chrometk.png 490w, https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2018\/04\/chrometk-320x87.png 320w\" sizes=\"auto, (max-width: 490px) 100vw, 490px\" \/><\/a><\/p>\n<p><iframe loading=\"lazy\" title=\"Open websites with Chrome with Python 1\" width=\"747\" height=\"420\" src=\"https:\/\/www.youtube.com\/embed\/wcMqCA37fIo?feature=oembed&amp;enablejsapi=1\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<p>The code is the following:<\/p>\n<pre class=\"lang:default decode:true \">import tkinter as tk\r\nimport webbrowser\r\n\r\nclass Check:\r\n\tdef __init__(self, master, site):\r\n\t\t\"\"\"Creates checkbuttons to choose sites\"\"\"\r\n\t\tself.var = tk.IntVar()\r\n\t\tself.site = site\r\n\t\tself = tk.Checkbutton(\r\n\t\t\tmaster,\r\n\t\t\ttext = self.site,\r\n\t\t\tvariable = self.var,\r\n\t\t\tcommand=self.print_info\r\n\t\t\t).pack()\r\n\r\n\tdef print_info(self):\r\n\t\tprint(f\"site: {self.site}\\n {self.var.get()}\")\r\n\t\tif self.var.get() == 1:\r\n\t\t\tchecked.append(self.site)\r\n\t\telse:\r\n\t\t\tchecked.remove(self.site)\r\n\r\nclass App:\r\n\tdef __init__(self, sites):\r\n\t\t\"\"\"Creates window with checkbuttons\"\"\"\r\n\t\tc = []\r\n\t\tmaster = tk.Tk()\r\n\t\tfor s in sites:\r\n\t\t\tc.append(Check(master, s))\r\n\t\ttk.Button(master, text=\"Launch Chrome\", command = lambda: self.start()).pack()\r\n\t\tmaster.mainloop()\r\n\r\n\tdef start(self):\r\n\t\t\"\"\"Opens the browser with checked sites\"\"\"\r\n\t\tchrome = \"C:\/Program Files (x86)\/Google\/Chrome\/Application\/chrome.exe %s\" \r\n\t\tw = webbrowser.get(chrome)\r\n\t\tfor site in checked:\r\n\t\t\tw.open(site)\r\n\r\nchecked = []\r\napp = App([\"www.google.com\",\r\n           \"www.gmail.com\",\r\n           \"https:\\\\pythonprogramming.altervista.org\"])<\/pre>\n<p>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.<\/p>\n<p><a href=\"https:\/\/pythonprogramming.altervista.org\/how-to-open-a-web-page-in-the-browser-using-chrome-with-python-and-webbrowser\/\">Go to read the original post clicking this link<\/a><\/p>\n<p><iframe loading=\"lazy\" title=\"Open link in Chrome with Python and webbrowser.\" width=\"747\" height=\"560\" src=\"https:\/\/www.youtube.com\/embed\/l7A-pxbQS2o?feature=oembed&amp;enablejsapi=1\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<h2>Opening web pages without tkinter<\/h2>\n<p>With the following code we can open the windows, but just with the console, without using tkinter.<\/p>\n<pre class=\"lang:default decode:true \">import tkinter as tk\r\nimport webbrowser\r\n\r\n\r\nsites = [\"https:\/\/pythonprogramming.altervista.org\/wp-admin\/post.php?post=122&amp;action=edit\",\r\n        \"https:\/\/pythonprogramming.altervista.org\/wp-admin\",\r\n        \"https:\/\/aziendaitalia.altervista.org\/wp-admin\"]\r\n\r\nfor n, s in enumerate(sites):\r\n    print(n,s)\r\n\r\nprint(\"Write the number of the site you wanto to open, separated by a space\")\r\nchecked = input(\"Wich site you want to open?\")\r\nchecked = [sites[int(f)] for f in checked.split(\" \")]\r\n\r\n\r\ndef openweb():\r\n    chromedir= 'C:\/Program Files (x86)\/Google\/Chrome\/Application\/chrome.exe %s'\r\n    for site in checked:\r\n        webbrowser.get(chromedir).open(site)\r\n\r\nopenweb()<\/pre>\n<p>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.<\/p>\n<h1 style=\"text-align: center;\"><a href=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/08\/bitmap.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-2821\" src=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/08\/bitmap.png\" alt=\"\" width=\"302\" height=\"160\" \/><\/a><\/h1>\n<h1>Add new sites to tkinter app<\/h1>\n<p>Ok, now it&#8217;s time to make this app more &#8220;user friendly&#8221;. Let&#8217;s add the chance to add sites to the ones that we put in the code with:<\/p>\n<pre class=\"lang:default decode:true \">sites = [\"https:\/\/pythonprogramming.altervista.org\/wp-admin\/post.php?post=122&amp;action=edit\",\r\n        \"https:\/\/pythonprogramming.altervista.org\/wp-admin\",\r\n        \"https:\/\/aziendaitalia.altervista.org\/wp-admin\"]<\/pre>\n<p>We could add them into this script, but we want to do it from the GUI.<\/p>\n<p>Let&#8217;s make it following these steps:<\/p>\n<p>Here the user will digit the address he wants to add:<\/p>\n<pre class=\"lang:default decode:true\">    l = tk.Label(master, text=\"Add a new site\").pack()\r\n    e = tk.Entry(master)\r\n    e.pack()\r\n<\/pre>\n<p>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.<\/p>\n<pre class=\"lang:default decode:true \">    e.bind(\"&lt;Return&gt;\", addsite)<\/pre>\n<p>Now we need to add the addsite function<\/p>\n<pre class=\"lang:default decode:true \">def addsite(event):\r\n    global c,e,master\r\n    sites.append(e.get())\r\n    c.append(Check(master, e.get()))\r\n    with open(\"links.txt\", \"a\") as file:\r\n        file.write(e.get() + \"\\n\")<\/pre>\n<p>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).<\/p>\n<p>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.<\/p>\n<pre class=\"lang:default decode:true\">with open(\"links.txt\") as file:\r\n    for line in file:\r\n        sites.append(line)<\/pre>\n<p>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&#8217;t want anymore or even delete all of them.<\/p>\n<p>Next time we will add a way to delete the address from the GUI of the app.<\/p>\n<h2>Let&#8217;s take a look at the code to open web pages with tkinter<\/h2>\n<pre class=\"lang:default decode:true \"># Original post:\r\n\"\"\"\r\n<blockquote class=\"wp-embedded-content\" data-secret=\"AS6akVerMn\"><a href=\"https:\/\/pythonprogramming.altervista.org\/how-to-open-a-web-page-in-the-browser-using-chrome-with-python-and-webbrowser\/\">Open Chrome with Python and webbrowser<\/a><\/blockquote><iframe loading=\"lazy\" class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; clip: rect(1px, 1px, 1px, 1px);\" title=\"&#8220;Open Chrome with Python and webbrowser&#8221; &#8212; python programming\" src=\"https:\/\/pythonprogramming.altervista.org\/how-to-open-a-web-page-in-the-browser-using-chrome-with-python-and-webbrowser\/embed\/#?secret=JD0YSjbdGm#?secret=AS6akVerMn\" data-secret=\"AS6akVerMn\" width=\"600\" height=\"338\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>\r\n\"\"\"\r\n\r\n\r\nimport tkinter as tk\r\nimport webbrowser\r\n\r\ndef openweb(browser=\"\"):\r\n    if browser == \"chrome\":\r\n            chromedir= 'C:\/Program Files (x86)\/Google\/Chrome\/Application\/chrome.exe %s'\r\n    for site in checked:\r\n        webbrowser.get(chromedir).open(site)\r\n\r\nclass Check:\r\n    def __init__(self, master, site):\r\n        self.var = tk.IntVar()\r\n        self.site = site\r\n        self = tk.Checkbutton(\r\n            master,\r\n            text=self.site,\r\n            variable=self.var,\r\n            command=self.print_info).pack()\r\n\r\n    def print_info(self):\r\n        print(f\"status of {self.site}: {self.var.get()}\")\r\n        if self.var.get() == 1:\r\n            checked.append(self.site)\r\n        else:\r\n            checked.remove(self.site)\r\n\r\ndef addsite(event):\r\n    global c,e,master\r\n    sites.append(e.get())\r\n    c.append(Check(master, e.get()))\r\n    with open(\"links.txt\", \"a\") as file:\r\n        file.write(e.get() + \"\\n\")\r\n\r\n\r\n\r\nsites = [\"https:\/\/pythonprogramming.altervista.org\/wp-admin\/post.php?post=122&amp;action=edit\",\r\n        \"https:\/\/pythonprogramming.altervista.org\/wp-admin\",\r\n        \"https:\/\/aziendaitalia.altervista.org\/wp-admin\"]\r\nwith open(\"links.txt\") as file:\r\n    for line in file:\r\n        sites.append(line)\r\n\r\nchecked = []\r\n\r\ndef start():\r\n    global c,e,master\r\n    c = []\r\n    master = tk.Tk()\r\n    for s in sites:\r\n        c.append(Check(master, s))\r\n    tk.Button(master, text=\"Launch browser\", command = lambda: openweb(\"chrome\")).pack()\r\n    l = tk.Label(master, text=\"Add a new site\").pack()\r\n    e = tk.Entry(master)\r\n    e.pack()\r\n    e.bind(\"&lt;Return&gt;\", addsite)\r\n    master = tk.mainloop()\r\n\r\nstart()<\/pre>\n<p>This is an example of the window<\/p>\n<figure id=\"attachment_2815\" aria-describedby=\"caption-attachment-2815\" style=\"width: 490px\" class=\"wp-caption alignnone\"><a href=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/08\/chrome003.png\"><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-2815\" src=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/08\/chrome003.png\" alt=\"\" width=\"490\" height=\"238\" srcset=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/08\/chrome003.png 490w, https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/08\/chrome003-320x155.png 320w\" sizes=\"auto, (max-width: 490px) 100vw, 490px\" \/><\/a><figcaption id=\"caption-attachment-2815\" class=\"wp-caption-text\">tkinter app webbrowser<\/figcaption><\/figure>\n<p>This is the link.txt content after adding the 2 sites you see in the image above:<\/p>\n<p><a href=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/08\/text.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-2817\" src=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/08\/text.png\" alt=\"\" width=\"499\" height=\"291\" srcset=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/08\/text.png 499w, https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/08\/text-320x187.png 320w\" sizes=\"auto, (max-width: 499px) 100vw, 499px\" \/><\/a><\/p>\n","protected":false},"excerpt":{"rendered":"Hello, I revisited a post I made last year to add some &#8216;features&#8217; to that very simple script to open chrome with python \n<a class=\"moretag\" href=\"https:\/\/pythonprogramming.altervista.org\/open-sites-with-python-and-webbrowser\/\"> [...]<\/a>","protected":false},"author":1,"featured_media":2811,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_crdt_document":"","footnotes":""},"categories":[1],"tags":[],"class_list":["post-2803","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-examples"],"avopt_banners_inside_post":true,"avopt_banners_on_page":true,"av_copy_from":"","av_sharing_message":"","av_sharing_allowed":false,"av_sharing_on":{"fb":[],"tw":[]},"av_allow_affiliate_banner":false,"av_allow_affiliate_multi_banner":false,"av_show_affiliation_buy_button":false,"av_post_rating":true,"av_have_post_rating_value":false,"av_is_artificial_intelligence_content":false,"_links":{"self":[{"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/posts\/2803","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/comments?post=2803"}],"version-history":[{"count":12,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/posts\/2803\/revisions"}],"predecessor-version":[{"id":2825,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/posts\/2803\/revisions\/2825"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/media\/2811"}],"wp:attachment":[{"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/media?parent=2803"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/categories?post=2803"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/tags?post=2803"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}