How do I set the desktop background in python? (windows)

后端 未结 1 957
挽巷
挽巷 2020-12-11 10:25

This is what I\'m trying:

import ctypes
import os
drive = \"F:\\\\\"
folder = \"Keith\'s Stuff\"
image = \"midi turmes.png\"
image_path = os.path.join(drive,         


        
相关标签:
1条回答
  • 2020-12-11 11:02

    The following works for me. I'm using Windows 10 64-bit and Python 3.

    import os
    import ctypes
    from ctypes import wintypes
    
    drive = "c:\\"
    folder = "test"
    image = "midi turmes.png"
    image_path = os.path.join(drive, folder, image)
    
    SPI_SETDESKWALLPAPER  = 0x0014
    SPIF_UPDATEINIFILE    = 0x0001
    SPIF_SENDWININICHANGE = 0x0002
    
    user32 = ctypes.WinDLL('user32')
    SystemParametersInfo = user32.SystemParametersInfoW
    SystemParametersInfo.argtypes = ctypes.c_uint,ctypes.c_uint,ctypes.c_void_p,ctypes.c_uint
    SystemParametersInfo.restype = wintypes.BOOL
    print(SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, image_path, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE))
    

    The important part is to make sure to use a Unicode string for image_path if using SystemParametersInfoW, and a byte string if using SystemParametersInfoA. Remember that in Python 3 strings are default Unicode.

    It is also good practice to set argtypes and restype as well. You can even "lie" and set the third argtypes parameter to c_wchar_p for SystemParametersInfoW and then ctypes will validate that you are passing a Unicode string and not a byte string.

    0 讨论(0)
提交回复
热议问题