A Random Wikipedia Article Generator GUI In Python

PHOTO EMBED

Wed Jul 19 2023 14:58:30 GMT+0000 (Coordinated Universal Time)

Saved by @pythonHub #python #python-hub #day9

import requests
import wikipedia
from customtkinter import *
from tkinter import Label
import tkinter.messagebox as messagebox
import tkinter.font as tkfont
import webbrowser


class WikipediaArticle(CTk):
    def __init__(self):
        """Initialize the WikipediaArticle application."""
        super().__init__()
        # font for link
        self.custom_font = tkfont.Font(size=10, underline=True)
        # setting an empty label to avoid errors
        self.link = CTkLabel(self, text="")
        # button for generating random article
        self.get_article = CTkButton(self, text="Random Stuff", command=self.random_article_t_summary)
        self.get_article.grid(row=3, column=1 ,padx=10,pady=10)
        # button to copy article link
        self.copy_t = CTkButton(self, text="Copy Link", command=self.copy_text, fg_color="transparent")
        self.copy_t.grid(row=3, column=2 ,padx=10,pady=10)
        # button to open link in browser
        self.open_i = CTkButton(self, text="Open in browser", command=self.open_link)
        self.open_i.grid(row=3, column=0 ,padx=10,pady=10)

    def random_article_t_summary(self):
        """Generate a random Wikipedia article and display its title, summary, and link.
        uses the self.summarize_wikipedia_article() method"""
        url = requests.get("https://en.wikipedia.org/wiki/Special:Random")
        
        article_link = url.url
        title_and_summary = self.summarize_wikipedia_article(article_link)

        if title_and_summary:
            # getting link and title
            self.link = Label(self, text=article_link, fg="blue", font=self.custom_font)
            self.title = CTkLabel(self, text=title_and_summary[0])
            # getting summary
            self.random_article = CTkTextbox(self)
            self.random_article.insert("0.0", title_and_summary[1])
            self.random_article.configure(state="disabled")
            # packing title, summary, and link
            self.title.grid(row=0, column=1, padx=10)
            self.random_article.grid(row=1, column=1 ,padx=10,pady=10)
            self.link.grid(row=2, column=0, padx=10)
        
    def summarize_wikipedia_article(self,article_link):
        """
        Summarize a Wikipedia article based on its link.

        Args:
            article_link (str): The link to the Wikipedia article.

        Returns:
            list: A list containing the page title and summary of the article, or None if the article is not found.
        """
        # Extract the page title from the article link
        page_title = article_link.split("/")[-1]

        try:
            # Get the Wikipedia page based on the page title
            page = wikipedia.page(page_title)

            # Retrieve the summary of the page
            summary = page.summary

            return [page_title,summary]

        except wikipedia.exceptions.PageError:
            message = CTkLabel(self, text="Something went wrong! Try Again!")
            message.grid(row=4, column=1,padx=10, pady=10)
            return None
        
    def copy_text(self):
        # Get the text from the label
        text = self.link.cget("text")

        # Set the text to the clipboard
        self.clipboard_clear()
        self.clipboard_append(text)

        messagebox.showinfo("Copy", "Text copied to clipboard!")

    def open_link(self):
        try:
            webbrowser.open(self.link.cget("text"))
        except Exception:
            message = CTkLabel(self, text="Get the link first!")
            message.grid(row=4, column=1,padx=10, pady=10)
        
if __name__ == "__main__":
    app = WikipediaArticle()
    app.mainloop()
content_copyCOPY

https://python-hub.com/day-9-a-random-wikipedia-article-generator-gui-in-python/