【问题标题】:Change Windows 10 background in Python 3在 Python 3 中更改 Windows 10 背景
【发布时间】:2019-05-21 13:19:59
【问题描述】:

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

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

【问题讨论】:

  • 我正在运行 macOS,但请检查您是否可以将其用作参考。 techwalla.com/articles/script-to-change-desktop-background。它涉及 2 个步骤。更改所需桌面壁纸的路径并使用 user32.dll,UpdatePerUserSystemParameters", 1, True 发送系统更新命令。此更新命令包含在我阅读的大多数指南中。

标签: python python-3.x windows windows-10 ctypes


【解决方案1】:

对于 64 位窗口,使用:

ctypes.windll.user32.SystemParametersInfoW

对于 32 位窗口,使用:

ctypes.windll.user32.SystemParametersInfoA

如果你用错了,你会得到一个黑屏。您可以在控制面板 -> 系统和安全 -> 系统中找到您使用的版本。

你也可以让你的脚本选择正确的:

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)

更新:

我对上述内容进行了疏忽。正如 cmets 中所展示的@Mark Tolonen,它取决于 ANSI 和 UNICODE 路径字符串,而不是操作系统类型。

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

ctypes.windll.user32.SystemParametersInfoA

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

ctypes.windll.user32.SystemParametersInfoW

@Mark Tolonen's 答案和另一个 answer 中的 argtypes 也可以更好地突出显示这一点。

【讨论】:

  • 真正的问题不是定义参数类型。 A 版本的第三个参数采用字节字符串,W 版本采用 Unicode 字符串。如果调用正确,无论操作系统类型如何,您都可以同时使用 A 和 W。
【解决方案2】:

SystemParametersInfoA 采用 ANSI 字符串(bytes 在 Python 3 中键入)。

SystemParametersInfoW 采用 Unicode 字符串(str 在 Python 3 中输入)。

所以使用:

path = b'C:\\Users\\Patrick\\Desktop\\0200200220.jpg'
ctypes.windll.user32.SystemParametersInfoA(20, 0, path, 3)

或:

path = 'C:\\Users\\Patrick\\Desktop\\0200200220.jpg'
ctypes.windll.user32.SystemParametersInfoW(20, 0, path, 3)

您可以设置 argtypes 来进行参数检查。第三个参数记录为LPVOID,但您可以更具体地进行类型检查:

from ctypes import *
windll.user32.SystemParametersInfoW.argtypes = c_uint,c_uint,c_wchar_p,c_uint
windll.user32.SystemParametersInfoA.argtypes = c_uint,c_uint,c_char_p,c_uint

【讨论】:

    猜你喜欢
    • 2021-05-27
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    相关资源
    最近更新 更多