我正在尝试从 MomentumDash 下载一些图像(仅用于教育目的)。 我编写了以下 python 代码:
import urllib
import os
import random
#Chooses an image between 1 to 14
choice=random.randint(01,14)
print choice
#Downloads images
a=urllib.urlretrieve("https://momentumdash.com/backgrounds/"+"%02d" % (choice,)+".jpg", str(choice)+".jpg")
print a #Tells the image
#Getting the location of the saved image
cwd = os.getcwd()
random=random.choice(os.listdir(cwd))
file =cwd+ '\\' +random
#Making the image to desktop image
import ctypes
SPI_SETDESKWALLPAPER = 20
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER , 0, file, 3)
问题是这个程序设置图像的概率是 1/7 左右。
大多数时候它会显示黑色背景屏幕。
我哪里错了?
最佳答案
尝试以下操作。这可确保过滤目录列表,只为您提供 jpg
文件。从中随机抽取一个条目。 os.path.join()
还用于安全地将您的路径和名称连接在一起。
import urllib
import os
import random
import ctypes
#Chooses an image between 1 to 14
choice = random.randint(1, 14)
#Downloads images
download_name = "{:02}.jpg".format(choice)
a = urllib.urlretrieve("https://momentumdash.com/backgrounds/{}".format(download_name), download_name)
#Getting the location of the saved image
cwd = os.getcwd()
#Filter the list to only give JPG image files
image_files = [f for f in os.listdir(cwd) if os.path.splitext(f)[1].lower() == ".jpg"]
random_image = random.choice(image_files)
full_path = os.path.join(cwd, random_image)
#Making the image to desktop image
SPI_SETDESKWALLPAPER = 20
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER , 0, full_path, 3)
文件列表是使用 Python 的 list comprehension 过滤的特征。这是一种从现有项目构建新列表的方法。在这种情况下,它使用可选的 if
语句仅在新列表中包含扩展名为 .jpg
的文件。
关于python - 下载的图片并不总是设置为背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42095109/