下载的图像不会始终设置为背景?

时间:2017-02-07 16:31:07

标签: python windows random ctypes urllib

我正在尝试从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 ish 大多数时候它都会产生黑色背景屏幕 我哪里错了?

2 个答案:

答案 0 :(得分:2)

尝试以下方法。这可确保过滤目录列表,仅为您提供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的文件。

答案 1 :(得分:1)

尝试以下方法:

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的文件夹,将所有图像保存在那里,然后随机选择一个。