本文介绍了在Python 3中更改Windows 10背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找通过python脚本更改Windows 10桌面墙纸的最佳方法.当我尝试运行此脚本时,桌面背景变成纯黑色.

I've been trying to find the best way to change the Windows 10 Desktop wallpaper through a python script. When I try to run this script, the desktop background turns to a solid black color.

import ctypes

path = 'C:\\Users\\Patrick\\Desktop\\0200200220.jpg'

def changeBG(path):
    SPI_SETDESKWALLPAPER = 20
    ctypes.windll.user32.SystemParametersInfoA(20, 0, path, 3)
    return;

changeBG(path)

我该怎么做才能解决此问题?我正在使用python3

What can I do to fix this? I'm using python3

推荐答案

对于64位窗口,请使用:

For 64 bit windows, use:

ctypes.windll.user32.SystemParametersInfoW

对于32位窗口,请使用:

for 32 bit windows, use:

ctypes.windll.user32.SystemParametersInfoA

如果使用错误的屏幕,则会出现黑屏.您可以在控制面板->系统和安全性->系统中找到要使用的版本.

If you use the wrong one, you will get a black screen. You can find out which version your using in Control Panel -> System and Security -> System.

您还可以使脚本选择正确的脚本:

You could also make your script choose the correct one:

import struct
import ctypes

PATH = 'C:\\Users\\Patrick\\Desktop\\0200200220.jpg'
SPI_SETDESKWALLPAPER = 20

def is_64bit_windows():
    """Check if 64 bit Windows OS"""
    return struct.calcsize('P') * 8 == 64

def changeBG(path):
    """Change background depending on bit size"""
    if is_64bit_windows():
        ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, PATH, 3)
    else:
        ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, PATH, 3)

changeBG(PATH)

更新:

我已对上述内容进行了疏忽.正如 @Mark Tolonen 在评论中所示,取决于ANSI和UNICODE路径字符串,而不取决于OS类型.

I've made an oversight with the above. As @Mark Tolonen demonstrated in the comments, it depends on ANSI and UNICODE path strings, not the OS type.

如果使用字节字符串路径,例如 b'C:\\ Users \\ Patrick \\ Desktop \\ 0200200220.jpg',请使用:

If you use the byte strings paths, such as b'C:\\Users\\Patrick\\Desktop\\0200200220.jpg', use:

ctypes.windll.user32.SystemParametersInfoA

否则,您可以将其用于普通的unicode路径:

Otherwise you can use this for normal unicode paths:

ctypes.windll.user32.SystemParametersInfoW

使用 @Mark Tolonen的argtypes也可以更好地突出显示答案,以及其他 answer

这篇关于在Python 3中更改Windows 10背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 05:55