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

标签 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 左右。
大多数时候它会显示黑色背景屏幕。
我哪里错了?

最佳答案

尝试以下操作。这可确保过滤目录列表,只为您提供 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/

相关文章:

random - 在 JMeter 中选择随机分割变量

c - 我需要生成一组97到122之间的随机数

python - pandas 每组特定值的频率

python - alembic - 使用包资源作为 script_location 的示例

c++ - Windows - VC++ - 不能在静态构建中使用 "_ASSERTE"

windows - 如何检测文件夹是否为空(Windows 批处理文件)?

python - Python 中的 Kendall 一致性系数 (W)

python - 如何从字符串列表中删除单词列表?

c# - 如何获取 Windows 服务的命令行参数?

java - 随机(Java 7)中的 181783497276652981 和 8682522807148012 是什么?