本文目录导读:

我来帮你写一个自动切换壁纸的脚本,这里提供几种常见的实现方式:
Windows PowerShell 脚本
# AutoWallpaper.ps1
# Windows自动切换壁纸脚本
$wallpaperFolder = "C:\Wallpapers" # 壁纸文件夹路径
$interval = 60 # 切换间隔(秒)
# 获取所有图片文件
$images = Get-ChildItem -Path $wallpaperFolder -Include *.jpg,*.jpeg,*.png,*.bmp -Recurse
if ($images.Count -eq 0) {
Write-Host "没有找到图片文件" -ForegroundColor Red
exit
}
# 设置壁纸函数
function Set-Wallpaper {
param($ImagePath)
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class Wallpaper {
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int SystemParametersInfo(
int uAction, int uParam, string lpvParam, int fuWinIni);
}
"@
$SPI_SETDESKWALLPAPER = 0x0014
$SPIF_UPDATEINIFILE = 0x01
$SPIF_SENDWININICHANGE = 0x02
[Wallpaper]::SystemParametersInfo($SPI_SETDESKWALLPAPER, 0, $ImagePath,
$SPIF_UPDATEINIFILE -bor $SPIF_SENDWININICHANGE) | Out-Null
}
# 主循环
Write-Host "开始自动切换壁纸 (Ctrl+C 停止)" -ForegroundColor Green
while ($true) {
$randomImage = Get-Random -InputObject $images
Set-Wallpaper -ImagePath $randomImage.FullName
Write-Host "已切换: $($randomImage.Name) - $(Get-Date -Format 'HH:mm:ss')"
Start-Sleep -Seconds $interval
}
Bash 脚本 (Linux/macOS)
#!/bin/bash
# auto_wallpaper.sh
# Linux/macOS自动切换壁纸脚本
WALLPAPER_DIR="$HOME/Pictures/Wallpapers"
INTERVAL=300 # 切换间隔(秒)
# 获取图片列表
get_images() {
find "$WALLPAPER_DIR" -type f \( \
-name "*.jpg" -o \
-name "*.jpeg" -o \
-name "*.png" -o \
-name "*.gif" -o \
-name "*.bmp" \) 2>/dev/null
}
# 设置壁纸(根据桌面环境)
set_wallpaper() {
local image="$1"
# 检测GNOME
if command -v gsettings > /dev/null 2>&1; then
gsettings set org.gnome.desktop.background picture-uri "file://$image"
gsettings set org.gnome.desktop.background picture-uri-dark "file://$image"
# 检测KDE
elif command -v plasma-apply-wallpaperimage > /dev/null 2>&1; then
plasma-apply-wallpaperimage "$image"
# 检测macOS
elif [[ "$OSTYPE" == "darwin"* ]]; then
osascript -e "tell application \"System Events\" to set picture of every desktop to \"$image\""
# 使用feh(轻量级窗口管理器)
elif command -v feh > /dev/null 2>&1; then
feh --bg-scale "$image"
else
echo "无法检测到支持的桌面环境"
exit 1
fi
}
# 主循环
echo "开始自动切换壁纸 (Ctrl+C 停止)"
IMAGES=($(get_images))
if [ ${#IMAGES[@]} -eq 0 ]; then
echo "没有找到图片文件"
exit 1
fi
while true; do
# 随机选择一张图片
RANDOM_IMAGE="${IMAGES[$RANDOM % ${#IMAGES[@]}]}"
set_wallpaper "$RANDOM_IMAGE"
echo "已切换: $(basename "$RANDOM_IMAGE") - $(date '+%H:%M:%S')"
sleep "$INTERVAL"
done
Python 跨平台脚本
#!/usr/bin/env python3
"""
Auto Wallpaper Switcher
跨平台自动壁纸切换脚本
"""
import os
import random
import time
import platform
import subprocess
import ctypes
import glob
from pathlib import Path
class WallpaperSwitcher:
def __init__(self, wallpaper_dir, interval=300):
"""
初始化壁纸切换器
Args:
wallpaper_dir: 壁纸文件夹路径
interval: 切换间隔(秒)
"""
self.wallpaper_dir = Path(wallpaper_dir)
self.interval = interval
self.images = self._get_images()
self.system = platform.system()
if not self.images:
raise ValueError("没有找到图片文件")
def _get_images(self):
"""获取所有支持的图片文件"""
image_extensions = ['*.jpg', '*.jpeg', '*.png', '*.bmp', '*.gif']
images = []
for ext in image_extensions:
images.extend(self.wallpaper_dir.glob(f'**/{ext}'))
return images
def set_wallpaper_windows(self, image_path):
"""Windows系统设置壁纸"""
ctypes.windll.user32.SystemParametersInfoW(
0x0014, # SPI_SETDESKWALLPAPER
0,
str(image_path),
0x01 | 0x02 # SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE
)
def set_wallpaper_linux(self, image_path):
"""Linux系统设置壁纸"""
if os.environ.get('XDG_CURRENT_DESKTOP', '').lower() == 'gnome':
subprocess.run(['gsettings', 'set', 'org.gnome.desktop.background',
'picture-uri', f'file://{image_path}'])
else:
subprocess.run(['feh', '--bg-scale', str(image_path)])
def set_wallpaper_mac(self, image_path):
"""macOS系统设置壁纸"""
script = f"""
tell application "System Events"
set picture of every desktop to "{image_path}"
end tell
"""
subprocess.run(['osascript', '-e', script])
def change_wallpaper(self):
"""切换壁纸"""
image = random.choice(self.images)
try:
if self.system == "Windows":
self.set_wallpaper_windows(image)
elif self.system == "Linux":
self.set_wallpaper_linux(image)
elif self.system == "Darwin":
self.set_wallpaper_mac(image)
else:
raise OSError(f"不支持的系统: {self.system}")
print(f"[{time.strftime('%H:%M:%S')}] 已切换: {image.name}")
except Exception as e:
print(f"切换失败: {e}")
def run(self):
"""运行主循环"""
print(f"开始自动切换壁纸 (Ctrl+C 停止)")
print(f"壁纸目录: {self.wallpaper_dir}")
print(f"切换间隔: {self.interval}秒")
try:
while True:
self.change_wallpaper()
time.sleep(self.interval)
except KeyboardInterrupt:
print("\n壁纸切换已停止")
if __name__ == "__main__":
# 配置
WALLPAPER_DIR = os.path.expanduser("~/Pictures/Wallpapers")
INTERVAL_SECONDS = 300 # 5分钟
switcher = WallpaperSwitcher(WALLPAPER_DIR, INTERVAL_SECONDS)
switcher.run()
简单的BAT批处理脚本 (Windows)
@echo off自动壁纸切换器
color 0A
set "WALLPAPER_DIR=C:\Wallpapers"
set /a INTERVAL=60
echo ========================================
echo 自动壁纸切换器 v1.0
echo ========================================
echo.
echo 壁纸目录: %WALLPAPER_DIR%
echo 切换间隔: %INTERVAL% 秒
echo 按 Ctrl+C 停止
echo.
:main
for /f "delims=" %%i in ('dir /b /s "%WALLPAPER_DIR%\*.jpg" "%WALLPAPER_DIR%\*.jpeg" "%WALLPAPER_DIR%\*.png" 2^>nul') do (
set /a random_index = %random% %%
set "wallpaper=%%i"
powershell -command "Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public class Wallpaper { [DllImport(\"user32.dll\")] public static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni); }'; [Wallpaper]::SystemParametersInfo(0x0014, 0, \"%wallpaper%\", 0x01 -bor 0x02)" >nul
echo [%date% %time%] 已切换: %%~nxi
timeout /t %INTERVAL% /nobreak >nul
)
goto :main
使用建议
- 创建壁纸文件夹:将喜欢的图片放入指定文件夹
- 调整切换间隔:根据个人需求修改间隔时间
- 设置为开机启动:
- Windows: 创建快捷方式放入启动文件夹
- Linux: 添加到 systemd 服务或 crontab
- macOS: 创建 LaunchAgent
高级功能扩展
你可以根据需求添加:
- 使用 Bing 每日壁纸
- 根据时间段切换明亮/暗色壁纸
- 记录切换历史
- 支持多显示器
- 添加图片预处理(缩放、裁剪等)
需要我帮你实现特定功能或适配特定系统吗?