用python图片下载器 有界面
时间: 2024-03-10 10:51:05 浏览: 53
好的,以下是一个简单的Python图片下载器的带界面的代码示例:
```python
import requests
import os
import tkinter as tk
from tkinter import filedialog
class ImageDownloader:
def __init__(self, root):
self.root = root
self.url_label = tk.Label(self.root, text="Enter Image URL:")
self.url_label.pack()
self.url_entry = tk.Entry(self.root)
self.url_entry.pack()
self.folder_button = tk.Button(self.root, text="Select Folder", command=self.select_folder)
self.folder_button.pack()
self.download_button = tk.Button(self.root, text="Download Image", command=self.download_image)
self.download_button.pack()
self.selected_folder = ""
def select_folder(self):
self.selected_folder = filedialog.askdirectory()
def download_image(self):
url = self.url_entry.get()
if url == "":
tk.messagebox.showerror("Error", "Please enter an image URL.")
return
if self.selected_folder == "":
tk.messagebox.showerror("Error", "Please select a folder to save the image.")
return
response = requests.get(url)
if response.status_code != 200:
tk.messagebox.showerror("Error", f"Failed to download image from {url}")
return
image_name = url.split("/")[-1]
save_path = os.path.join(self.selected_folder, image_name)
with open(save_path, "wb") as f:
f.write(response.content)
tk.messagebox.showinfo("Success", f"Image saved to {save_path}")
if __name__ == "__main__":
root = tk.Tk()
root.title("Image Downloader")
downloader = ImageDownloader(root)
root.mainloop()
```
这个代码使用了`tkinter`库来创建一个简单的图形界面。界面包括一个文本框用于输入图片URL,一个按钮用于选择保存图片的文件夹,以及一个下载按钮。当下载按钮被点击时,程序会使用`requests`库下载图片并保存到指定的文件夹。如果下载成功,程序会弹出一个提示框告知用户图片已经保存到哪个文件夹。如果下载失败或用户没有输入URL或选择保存文件夹,则会弹出相应的错误提示框。
阅读全文