下载的图片并不总是设置为背景?

Downloaded Images does not set as background always?

我正在尝试从 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.

的文件

尝试以下操作:

import urllib
import os
import random
import ctypes

# Set up an output folder
out_folder = os.path.join(os.getcwd(), 'Backgrounds')

# Make it if it doesn't exist
if not os.path.isdir(out_folder):
    os.mkdir(out_folder)

# Loop through all values between 1 and 15
for choice in range(1,15):
    #Downloads images
    a = urllib.urlretrieve("https://momentumdash.com/backgrounds/" + "%02d" % (choice,)+".jpg",
                           os.path.join(out_folder, "{}.jpg".format(choice))
                           )

selected_wallpaper = random.choice(os.listdir(out_folder))

#Making the image to desktop image
SPI_SETDESKWALLPAPER = 20
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, os.path.join(out_folder, selected_wallpaper), 3)

这会在您当前的工作目录中创建一个名为 Backgrounds 的文件夹,将所有图像保存在那里,然后随机选择一个。