|
| 1 | +import tkinter as tk |
| 2 | +from tkinter import messagebox |
| 3 | +import os |
| 4 | +import requests |
| 5 | + |
| 6 | +def get_ext(url: str) -> str | None: |
| 7 | + exts = [".png", ".jpeg", ".jpg"] |
| 8 | + for ext in exts: |
| 9 | + if ext in url: |
| 10 | + return ext |
| 11 | + return None |
| 12 | + |
| 13 | +def download_img(): |
| 14 | + u = url_ent.get() |
| 15 | + n = name_ent.get() |
| 16 | + f = folder_ent.get() |
| 17 | + |
| 18 | + if not u or not n or not f: |
| 19 | + messagebox.showerror("Error", "Please fill in all fields.") |
| 20 | + return |
| 21 | + |
| 22 | + ext = get_ext(u) |
| 23 | + if not ext: |
| 24 | + messagebox.showerror("Error", "Invalid image URL.") |
| 25 | + return |
| 26 | + |
| 27 | + img_path = os.path.join(f, f"{n}{ext}") |
| 28 | + |
| 29 | + if os.path.isfile(img_path): |
| 30 | + messagebox.showerror("Error", "A file with the same name already exists.") |
| 31 | + return |
| 32 | + |
| 33 | + try: |
| 34 | + img_content = requests.get(u).content |
| 35 | + with open(img_path, "wb") as handler: |
| 36 | + handler.write(img_content) |
| 37 | + messagebox.showinfo("Success", f"Image downloaded to:\n{img_path}") |
| 38 | + except Exception as e: |
| 39 | + messagebox.showerror("Error", f"An error occurred: {e}") |
| 40 | + |
| 41 | +root = tk.Tk() |
| 42 | +root.title("Image Downloader") |
| 43 | +root.configure(bg="#1e1e1e") |
| 44 | + |
| 45 | +ul = tk.Label(root, text="Image URL:", bg="#1e1e1e", fg="white") |
| 46 | +ul.pack(pady=5) |
| 47 | + |
| 48 | +url_ent = tk.Entry(root, width=50) |
| 49 | +url_ent.pack(pady=5) |
| 50 | + |
| 51 | +nl = tk.Label(root, text="Image Name:", bg="#1e1e1e", fg="white") |
| 52 | +nl.pack(pady=5) |
| 53 | + |
| 54 | +name_ent = tk.Entry(root, width=50) |
| 55 | +name_ent.pack(pady=5) |
| 56 | + |
| 57 | +fl = tk.Label(root, text="Folder Path:", bg="#1e1e1e", fg="white") |
| 58 | +fl.pack(pady=5) |
| 59 | + |
| 60 | +folder_ent = tk.Entry(root, width=50) |
| 61 | +folder_ent.pack(pady=5) |
| 62 | + |
| 63 | +dl_btn = tk.Button(root, text="Download", command=download_img, bg="#303030", fg="white") |
| 64 | +dl_btn.pack(pady=10) |
| 65 | + |
| 66 | +root.mainloop() |
0 commit comments