from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from bs4 import BeautifulSoup import requests from customtkinter import * from PIL import Image from io import BytesIO class Motivator(CTk): """A GUI application for displaying random motivational images. When you are sad.""" def __init__(self) -> None: """ Initialize the Motivator GUI. Sets up the main window, question label, image label, and "Show Motivation" button. """ super().__init__() self.title("Random Motivation") self.geometry("600x600") # getting image self.question = CTkLabel(self, text="Are you sad? Click the button below.") self.question.grid(row=0, pady=10) self.sad_image = CTkImage(light_image=Image.open("images/sad.jpg"), size=(300,300)) # making image label self.ilsad = CTkLabel(self, image=self.sad_image, text="") # displaying image label self.ilsad.grid(row=1, pady=10) # Button to get a random motivational image self.show_motivation = CTkButton(self, text="Show Motivation", command=self.show_image).grid(row=2, pady=10) def get_img_url(self) -> str: """ Retrieve a random motivational image URL from Unsplash. Returns: str: The URL of the random motivational image. """ print("Getting image...") print("Please wait...") print("It might take a while...") # configuring chrome options so that the browser doesn't open up chrome_options = Options() chrome_options.add_argument("--headless") # Run Chrome in headless mode (no GUI) chrome_options.add_argument("--disable-gpu") # Required on some systems to avoid issues # setting up selenium' chrome driver to get the web page chrome_driver_path = "C:\Development\chromedriver.exe" service = Service(executable_path=chrome_driver_path) driver = webdriver.Chrome(service=service, options=chrome_options) # getting the webpage driver.get("https://source.unsplash.com/random/1080x810?motivational+quote") # getting its source code source = driver.page_source # making a soup of the html code to parse through it well soup = BeautifulSoup(source, 'html.parser') # finding the source url of the image img_url = soup.find('img')['src'] # quitting the driver (a good practice) driver.quit() print("Got the image showing it...") return img_url def show_image(self) -> None: """ Fetch and display the image got from self.get_img_url. Uses the get_img_url method to fetch the image URL and displays it on the GUI. """ # getting url from the above function img_url = self.get_img_url() # getting the source code of the image's web page response = requests.get(img_url) # converting code of image to an image readable by python image = Image.open(BytesIO(response.content)) # getting the image in customtkinter img = CTkImage(image, size=(540,405)) print("showing the image...") # showing the image with the use of label label = CTkLabel(self, image=img, text='') label.grid(row=1, pady=10) if __name__ == "__main__": app = Motivator() app.mainloop()