本文目录导读:

我来帮你写一个定时切换壁纸的脚本,这里提供几种方案的脚本,你可以根据你的操作系统选择。
Linux (使用cron + Python)
Python 脚本 (change_wallpaper.py)
#!/usr/bin/env python3
"""
Linux 定时切换壁纸脚本
支持 GNOME、KDE、XFCE 等常见桌面环境
"""
import os
import random
import subprocess
import sys
import glob
class WallpaperChanger:
def __init__(self, wallpaper_dir):
self.wallpaper_dir = wallpaper_dir
self.supported_formats = ['*.jpg', '*.jpeg', '*.png', '*.gif', '*.bmp']
def get_wallpapers(self):
"""获取所有支持的壁纸文件"""
wallpapers = []
for fmt in self.supported_formats:
wallpapers.extend(glob.glob(os.path.join(self.wallpaper_dir, fmt)))
return wallpapers
def get_desktop_environment(self):
"""检测桌面环境类型"""
if os.environ.get('GNOME_DESKTOP_SESSION_ID'):
return 'gnome'
elif os.environ.get('KDE_FULL_SESSION') == 'true':
return 'kde'
elif os.environ.get('XDG_CURRENT_DESKTOP'):
desktop = os.environ['XDG_CURRENT_DESKTOP'].lower()
if 'xfce' in desktop:
return 'xfce'
elif 'gnome' in desktop:
return 'gnome'
elif 'kde' in desktop:
return 'kde'
return 'unknown'
def set_gnome_wallpaper(self, wallpaper_path):
"""设置GNOME桌面环境的壁纸"""
subprocess.run([
'gsettings', 'set', 'org.gnome.desktop.background',
'picture-uri', f'file://{wallpaper_path}'
])
subprocess.run([
'gsettings', 'set', 'org.gnome.desktop.background',
'picture-uri-dark', f'file://{wallpaper_path}'
])
def set_kde_wallpaper(self, wallpaper_path):
"""设置KDE桌面环境的壁纸"""
subprocess.run([
'qdbus', 'org.kde.plasmashell', '/PlasmaShell',
'org.kde.PlasmaShell.evaluateScript',
f'''
var desktops = desktops();
for (var i = 0; i < desktops.length; i++) {{
desktops[i].wallpaperPlugin = "org.kde.image";
desktops[i].currentConfigGroup = ["Wallpaper", "org.kde.image", "General"];
desktops[i].writeConfig("Image", "file://{wallpaper_path}");
}}
'''
])
def set_xfce_wallpaper(self, wallpaper_path):
"""设置XFCE桌面环境的壁纸"""
subprocess.run([
'xfconf-query', '--channel', 'xfce4-desktop',
'--property', '/backdrop/screen0/monitor0/workspace0/last-image',
'--set', wallpaper_path
])
def change_wallpaper(self):
"""切换壁纸"""
wallpapers = self.get_wallpapers()
if not wallpapers:
print(f"错误:在 {self.wallpaper_dir} 目录中没有找到壁纸文件")
return False
# 随机选择一张壁纸
wallpaper = random.choice(wallpapers)
print(f"切换壁纸到: {wallpaper}")
# 获取桌面环境
desktop_env = self.get_desktop_environment()
print(f"检测到桌面环境: {desktop_env}")
# 根据桌面环境设置壁纸
try:
if desktop_env == 'gnome':
self.set_gnome_wallpaper(wallpaper)
elif desktop_env == 'kde':
self.set_kde_wallpaper(wallpaper)
elif desktop_env == 'xfce':
self.set_xfce_wallpaper(wallpaper)
else:
# 尝试通用的设置方法
subprocess.run([
'feh', '--bg-fill', wallpaper
])
print("壁纸切换成功!")
return True
except Exception as e:
print(f"设置壁纸时出错: {e}")
return False
def main():
# 配置壁纸目录(请修改为你的壁纸目录)
wallpaper_dir = os.path.expanduser("~/Pictures/wallpapers") # 修改为你的壁纸目录
# 如果不存在的目录,创建示例
if not os.path.exists(wallpaper_dir):
os.makedirs(wallpaper_dir)
print(f"壁纸目录不存在,已创建: {wallpaper_dir}")
print("请将你的壁纸图片放入该目录")
sys.exit(1)
changer = WallpaperChanger(wallpaper_dir)
changer.change_wallpaper()
if __name__ == "__main__":
main()
设置定时任务 (Cron)
#!/bin/bash # setup_cron.sh - 设置定时切换壁纸 # 1. 先给脚本添加执行权限 chmod +x change_wallpaper.py # 2. 获取脚本的绝对路径 SCRIPT_PATH=$(realpath change_wallpaper.py) # 3. 添加到crontab,设置每30分钟切换一次 (crontab -l 2>/dev/null; echo "*/30 * * * * /usr/bin/python3 $SCRIPT_PATH") | crontab - echo "定时切换壁纸已设置完成!每30分钟切换一次" echo "如需修改时间间隔,请编辑 crontab: crontab -e"
Windows (PowerShell + 任务计划程序)
PowerShell 脚本 (change_wallpaper.ps1)
# change_wallpaper.ps1
param(
[string]$WallpaperDir = "$env:USERPROFILE\Pictures\Wallpapers",
[string]$LogFile = "$env:LOCALAPPDATA\wallpaper_changer.log"
)
# 添加必要的 .NET 类型
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);
public const int SPI_SETDESKWALLPAPER = 20;
public const int SPIF_UPDATEINIFILE = 0x01;
public const int SPIF_SENDWININICHANGE = 0x02;
}
"@
function Write-Log {
param([string]$Message)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logEntry = "$timestamp - $Message"
Write-Host $logEntry
Add-Content -Path $LogFile -Value $logEntry
}
function Get-RandomWallpaper {
param([string]$Dir)
if (!(Test-Path $Dir)) {
Write-Log "壁纸目录不存在: $Dir"
return $null
}
$extensions = @("*.jpg", "*.jpeg", "*.png", "*.bmp", "*.gif")
$wallpapers = @()
foreach ($ext in $extensions) {
$wallpapers += Get-ChildItem -Path $Dir -Filter $ext -File
}
if ($wallpapers.Count -eq 0) {
Write-Log "目录中没有找到壁纸文件"
return $null
}
# 随机选择一张壁纸
$randomIndex = Get-Random -Minimum 0 -Maximum ($wallpapers.Count - 1)
return $wallpapers[$randomIndex].FullName
}
function Set-Wallpaper {
param([string]$WallpaperPath)
if ($null -eq $WallpaperPath -or !(Test-Path $WallpaperPath)) {
Write-Log "无效的壁纸路径"
return $false
}
try {
# 设置壁纸
$result = [Wallpaper]::SystemParametersInfo(
[Wallpaper]::SPI_SETDESKWALLPAPER,
0,
$WallpaperPath,
[Wallpaper]::SPIF_UPDATEINIFILE
)
if ($result) {
Write-Log "成功切换壁纸: $WallpaperPath"
return $true
} else {
Write-Log "设置壁纸失败"
return $false
}
} catch {
Write-Log "发生错误: $_"
return $false
}
}
# 主逻辑
Write-Log "=== 开始切换壁纸 ==="
$wallpaperPath = Get-RandomWallpaper -Dir $WallpaperDir
if ($null -ne $wallpaperPath) {
Set-Wallpaper -WallpaperPath $wallpaperPath
} else {
Write-Log "无法获取壁纸"
}
Write-Log "=== 完成 ==="
创建Windows任务计划
# setup_windows_task.ps1 - 设置Windows定时任务
# 脚本路径
$scriptPath = "$PSScriptRoot\change_wallpaper.ps1"
$taskName = "WallpaperChanger"
# 创建基本任务
$action = New-ScheduledTaskAction -Execute "PowerShell.exe" `
-Argument "-File `"$scriptPath`""
# 设置触发器 - 每30分钟执行一次
$trigger = New-ScheduledTaskTrigger -Once -At "00:00" `
-RepetitionInterval (New-TimeSpan -Minutes 30) `
-RepetitionDuration (New-TimeSpan -Days 3650)
# 设置启动条件
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries `
-DontStopIfGoingOnBatteries
# 注册任务
Register-ScheduledTask -TaskName $taskName `
-Action $action `
-Trigger $trigger `
-Settings $settings `
-Description "每30分钟自动切换壁纸"
Write-Host "Windows定时切换壁纸已设置完成!"
macOS (LaunchAgent)
创建macOS脚本 (change_wallpaper.sh)
#!/bin/bash
# change_wallpaper.sh - macOS定时切换壁纸
# 壁纸目录(请修改为你的壁纸目录)
WALLPAPER_DIR="$HOME/Pictures/Wallpapers"
# 创建日志目录
LOG_DIR="$HOME/Library/Logs"
mkdir -p "$LOG_DIR"
# 获取随机壁纸
random_wallpaper() {
local wallpapers=()
# 收集支持的文件类型
for ext in jpg jpeg png gif; do
while IFS= read -r file; do
wallpapers+=("$file")
done < <(find "$WALLPAPER_DIR" -type f -name "*.$ext" 2>/dev/null)
done
# 随机选择
if [ ${#wallpapers[@]} -gt 0 ]; then
echo "${wallpapers[$RANDOM % ${#wallpapers[@]}]}"
else
echo ""
fi
}
# 设置壁纸
set_wallpaper() {
local wallpaper="$1"
if [ ! -z "$wallpaper" ] && [ -f "$wallpaper" ]; then
# 使用osascript设置壁纸
osascript -e "tell application \"System Events\" to set picture of every desktop to \"$wallpaper\""
echo "$(date): 成功切换壁纸: $wallpaper" >> "$LOG_DIR/wallpaper_changer.log"
else
echo "$(date): 未找到壁纸文件" >> "$LOG_DIR/wallpaper_changer.log"
fi
}
# 主函数
main() {
# 检查壁纸目录
if [ ! -d "$WALLPAPER_DIR" ]; then
mkdir -p "$WALLPAPER_DIR"
echo "$(date): 壁纸目录不存在,已创建: $WALLPAPER_DIR" >> "$LOG_DIR/wallpaper_changer.log"
exit 1
fi
# 获取并设置壁纸
selected_wallpaper=$(random_wallpaper)
set_wallpaper "$selected_wallpaper"
}
# 执行主函数
main
创建LaunchAgent配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.user.wallpaperchanger</string>
<key>ProgramArguments</key>
<array>
<string>/bin/bash</string>
<string>/path/to/change_wallpaper.sh</string>
</array>
<!-- 每30分钟执行一次 -->
<key>StartInterval</key>
<integer>1800</integer>
<key>RunAtLoad</key>
<true/>
<key>StandardOutPath</key>
<string>/Users/yourname/Library/Logs/wallpaper_changer_stdout.log</string>
<key>StandardErrorPath</key>
<string>/Users/yourname/Library/Logs/wallpaper_changer_stderr.log</string>
</dict>
</plist>
安装LaunchAgent
# 加载LaunchAgent mkdir -p ~/Library/LaunchAgents cp com.user.wallpaperchanger.plist ~/Library/LaunchAgents/ launchctl load ~/Library/LaunchAgents/com.user.wallpaperchanger.plist # 如果修改了,可以重载 launchctl unload ~/Library/LaunchAgents/com.user.wallpaperchanger.plist launchctl load ~/Library/LaunchAgents/com.user.wallpaperchanger.plist
使用说明
- 准备工作:创建一个壁纸目录,放入你喜欢的壁纸图片
- 选择脚本:根据你的操作系统选择对应的脚本
- 修改配置:将脚本中的壁纸目录路径更改为你的实际路径
- 设置定时:
- Linux: 运行setup_cron.sh
- Windows: 运行setup_windows_task.ps1
- macOS: 安装LaunchAgent
自定义配置
你可以在脚本中调整:
- 切换频率(默认30分钟)
- 壁纸目录路径
- 图片格式支持
- 是否使用子目录
需要进一步调整的话,请告诉我你的具体需求!
版权声明:足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播