image.png (13.99 KB, 下载次数: 0)
下载附件
2024-1-1 18:11 上传
[Python] 纯文本查看 复制代码# -*- coding: utf-8 -*-
import os
import tkinter as tk
import urllib.request
from tkinter import messagebox
import requests
def download_bing_images():
# Bing 每日一图的 URL
url = 'https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=8&mkt=zh-CN'
response = requests.get(url)
data = response.json()
# 创建一个文件夹来保存图片
if not os.path.exists('bing_images'):
os.makedirs('bing_images')
# 遍历每日一图的数据并下载图片
for image_data in data['images']:
image_name = image_data['hsh']
image_url = f'https://cn.bing.com{image_data["url"]}'
try:
# 下载图片
with urllib.request.urlopen(image_url) as response:
image_data = response.read()
with open(f'bing_images/{image_name}.jpg', 'wb') as f:
f.write(image_data)
print(f'图片 {image_name}.jpg 已成功下载!')
progress_label.config(text=f'图片 {image_name}.jpg 已成功下载!')
except Exception as e:
print(f'下载失败:{str(e)}')
progress_label.config(text=f'下载失败:{str(e)}')
def on_button_click():
try:
# 清除之前的下载进度信息
progress_label.config(text='')
# 下载 Bing 每日一图
download_bing_images()
# 显示下载完成提示
progress_label.config(text='所有图片已下载完成!\n请查看当前目录对应的“bing_images”文件夹')
except Exception as e:
messagebox.showerror('错误', f'下载失败:\n{str(e)}')
# 创建主窗口
root = tk.Tk()
root.title('Bing 每日一图下载器')
root.geometry('400x300') # 设置窗口大小
# 创建按钮
button = tk.Button(root, text='下载 Bing 每日一图', command=on_button_click)
button.pack(padx=20, pady=20)
# 创建标签用于显示下载进度和结果
progress_label = tk.Label(root, text='')
progress_label.pack(padx=20, pady=20)
# 运行主循环
root.mainloop()
"