吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 136|回复: 3
收起左侧

[其他求助] 求一个用python写的win11自动换本地锁屏壁纸的程序

[复制链接]
lx136648 发表于 2025-3-31 12:48
100吾爱币
要求:可以设定更换时间(如30s,1min等),锁屏壁纸文件夹,图像适应模式(如填充等),要有开机自启动,启动后要能记住之前的设置,ui界面用pyqt5

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

太上忘情 发表于 2025-3-31 13:48
本帖最后由 太上忘情 于 2025-3-31 13:49 编辑

[Python] 纯文本查看 复制代码
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import sys
import os
import winreg
import configparser
from threading import Timer
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
                             QHBoxLayout, QLabel, QLineEdit, QPushButton,
                             QComboBox, QCheckBox, QFileDialog, QMessageBox)
from PyQt5.QtCore import Qt
 
class WallpaperChanger(QMainWindow):
    def __init__(self):
        super().__init__()
        self.timer = None
        self.config = configparser.ConfigParser()
        self.init_ui()
        self.load_settings()
        self.setWindowTitle("Auto Lock Screen Wallpaper Changer")
 
    def init_ui(self):
        main_widget = QWidget()
        layout = QVBoxLayout()
 
        # 时间间隔设置
        time_layout = QHBoxLayout()
        time_layout.addWidget(QLabel("更换间隔(秒):"))
        self.interval_input = QLineEdit()
        time_layout.addWidget(self.interval_input)
        layout.addLayout(time_layout)
 
        # 壁纸文件夹选择
        folder_layout = QHBoxLayout()
        self.folder_label = QLabel("未选择文件夹")
        folder_btn = QPushButton("选择壁纸文件夹")
        folder_btn.clicked.connect(self.select_folder)
        folder_layout.addWidget(folder_label)
        folder_layout.addWidget(folder_btn)
        layout.addLayout(folder_layout)
 
        # 适应模式
        mode_layout = QHBoxLayout()
        mode_layout.addWidget(QLabel("适应模式:"))
        self.mode_combo = QComboBox()
        self.mode_combo.addItems(["填充", "适应", "拉伸", "平铺", "居中"])
        mode_layout.addWidget(self.mode_combo)
        layout.addLayout(mode_layout)
 
        # 自启动选项
        self.auto_start_cb = QCheckBox("开机自动启动")
        layout.addWidget(self.auto_start_cb)
 
        # 控制按钮
        btn_layout = QHBoxLayout()
        self.start_btn = QPushButton("启动")
        self.start_btn.clicked.connect(self.toggle_changer)
        stop_btn = QPushButton("停止")
        stop_btn.clicked.connect(self.stop_changer)
        btn_layout.addWidget(self.start_btn)
        btn_layout.addWidget(stop_btn)
        layout.addLayout(btn_layout)
 
        main_widget.setLayout(layout)
        self.setCentralWidget(main_widget)
 
    def select_folder(self):
        folder = QFileDialog.getExistingDirectory(self, "选择壁纸文件夹")
        if folder:
            self.folder_label.setText(folder)
            self.save_settings()
 
    def toggle_changer(self):
        if self.start_btn.text() == "启动":
            if self.validate_settings():
                self.start_changer()
                self.start_btn.setText("暂停")
        else:
            self.stop_changer()
            self.start_btn.setText("启动")
 
    def validate_settings(self):
        if not os.path.isdir(self.folder_label.text()):
            QMessageBox.warning(self, "错误", "请选择有效的壁纸文件夹")
            return False
        try:
            int(self.interval_input.text())
        except ValueError:
            QMessageBox.warning(self, "错误", "请输入有效的数字间隔")
            return False
        return True
 
    def start_changer(self):
        interval = int(self.interval_input.text())
        self.timer = Timer(interval, self.change_wallpaper)
        self.timer.start()
        self.save_settings()
 
    def stop_changer(self):
        if self.timer:
            self.timer.cancel()
 
    def change_wallpaper(self):
        folder = self.folder_label.text()
        images = [f for f in os.listdir(folder) if f.lower().endswith(('.png', '.jpg', '.jpeg'))]
         
        if images:
            # 这里需要实现具体的壁纸更换逻辑
            # 示例代码,需要实际修改注册表项
            try:
                key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                                    r"SOFTWARE\Microsoft\Windows\CurrentVersion\PersonalizationCSP",
                                    0, winreg.KEY_WRITE)
                winreg.SetValueEx(key, "LockScreenImagePath", 0, winreg.REG_SZ, os.path.join(folder, images[0]))
                winreg.SetValueEx(key, "LockScreenImageUrl", 0, winreg.REG_SZ, os.path.join(folder, images[0]))
                winreg.CloseKey(key)
                QMessageBox.information(self, "成功", "壁纸已更换")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"更换失败: {str(e)}")
 
        # 重新启动定时器
        self.start_changer()
 
    def save_settings(self):
        self.config['DEFAULT'] = {
            'interval': self.interval_input.text(),
            'folder': self.folder_label.text(),
            'mode': self.mode_combo.currentIndex(),
            'auto_start': str(self.auto_start_cb.isChecked())
        }
        with open('config.ini', 'w') as configfile:
            self.config.write(configfile)
         
        # 处理开机启动
        self.set_auto_start(self.auto_start_cb.isChecked())
 
    def load_settings(self):
        if os.path.exists('config.ini'):
            self.config.read('config.ini')
            self.interval_input.setText(self.config.get('DEFAULT', 'interval', fallback='300'))
            self.folder_label.setText(self.config.get('DEFAULT', 'folder', fallback=''))
            self.mode_combo.setCurrentIndex(int(self.config.get('DEFAULT', 'mode', fallback=0)))
            self.auto_start_cb.setChecked(self.config.getboolean('DEFAULT', 'auto_start', fallback=False))
 
    def set_auto_start(self, enable):
        key_path = r"Software\Microsoft\Windows\CurrentVersion\Run"
        app_name = "WallpaperChanger"
        exe_path = os.path.abspath(sys.argv[0])
         
        try:
            key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path, 0, winreg.KEY_SET_VALUE)
            if enable:
                winreg.SetValueEx(key, app_name, 0, winreg.REG_SZ, exe_path)
            else:
                winreg.DeleteValue(key, app_name)
            winreg.CloseKey(key)
        except Exception as e:
            QMessageBox.warning(self, "警告", f"开机启动设置失败: {str(e)}")
 
    def closeEvent(self, event):
        self.save_settings()
        self.stop_changer()
        event.accept()
 
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = WallpaperChanger()
    window.show()
    sys.exit(app.exec_())
congcongzhidao 发表于 2025-3-31 17:42
[Python] 纯文本查看 复制代码
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import sys
import os
import json
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
                            QHBoxLayout, QPushButton, QLabel, QSpinBox,
                            QComboBox, QFileDialog)
from PyQt5.QtCore import QTimer, Qt
import winreg
import win32gui
import win32con
import random
from pathlib import Path
from cx_Freeze import setup, Executable
 
class LockscreenChanger(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("锁屏壁纸自动更换器")
        self.setFixedSize(400, 300)
         
        # 默认设置
        self.settings = {
            'folder_path': '',
            'interval': 30,
            'fit_mode': 'fill'
        }
         
        self.load_settings()
        self.init_ui()
        self.setup_autostart()
         
        # 设置定时器
        self.timer = QTimer()
        self.timer.timeout.connect(self.change_lockscreen)
        self.start_timer()
 
    def init_ui(self):
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout(central_widget)
 
        # 文件夹选择
        folder_layout = QHBoxLayout()
        self.folder_label = QLabel(self.settings['folder_path'] or "未选择文件夹")
        folder_btn = QPushButton("选择文件夹")
        folder_btn.clicked.connect(self.select_folder)
        folder_layout.addWidget(self.folder_label)
        folder_layout.addWidget(folder_btn)
        layout.addLayout(folder_layout)
 
        # 时间间隔设置
        interval_layout = QHBoxLayout()
        interval_layout.addWidget(QLabel("更换间隔(秒):"))
        self.interval_spin = QSpinBox()
        self.interval_spin.setRange(5, 3600)
        self.interval_spin.setValue(self.settings['interval'])
        self.interval_spin.valueChanged.connect(self.update_interval)
        interval_layout.addWidget(self.interval_spin)
        layout.addLayout(interval_layout)
 
        # 适应模式选择
        fit_layout = QHBoxLayout()
        fit_layout.addWidget(QLabel("适应模式:"))
        self.fit_combo = QComboBox()
        self.fit_combo.addItems(['填充', '适应', '拉伸', '平铺', '居中'])
        self.fit_combo.setCurrentText(self.get_fit_mode_text(self.settings['fit_mode']))
        self.fit_combo.currentTextChanged.connect(self.update_fit_mode)
        fit_layout.addWidget(self.fit_combo)
        layout.addLayout(fit_layout)
 
        # 状态显示
        self.status_label = QLabel("程序已启动")
        layout.addWidget(self.status_label)
 
    def select_folder(self):
        folder = QFileDialog.getExistingDirectory(self, "选择壁纸文件夹")
        if folder:
            self.settings['folder_path'] = folder
            self.folder_label.setText(folder)
            self.save_settings()
 
    def update_interval(self, value):
        self.settings['interval'] = value
        self.save_settings()
        self.start_timer()
 
    def update_fit_mode(self, text):
        mode_map = {'填充': 'fill', '适应': 'fit', '拉伸': 'stretch',
                   '平铺': 'tile', '居中': 'center'}
        self.settings['fit_mode'] = mode_map[text]
        self.save_settings()
 
    def get_fit_mode_text(self, mode):
        mode_map = {'fill': '填充', 'fit': '适应', 'stretch': '拉伸',
                   'tile': '平铺', 'center': '居中'}
        return mode_map.get(mode, '填充')
 
    def save_settings(self):
        settings_path = Path.home() / 'lockscreen_settings.json'
        with open(settings_path, 'w', encoding='utf-8') as f:
            json.dump(self.settings, f)
 
    def load_settings(self):
        settings_path = Path.home() / 'lockscreen_settings.json'
        if settings_path.exists():
            with open(settings_path, 'r', encoding='utf-8') as f:
                self.settings.update(json.load(f))
 
    def setup_autostart(self):
        app_path = sys.executable
        key_path = r'Software\Microsoft\Windows\CurrentVersion\Run'
         
        try:
            key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path, 0,
                                winreg.KEY_ALL_ACCESS)
            winreg.SetValueEx(key, 'LockscreenChanger', 0, winreg.REG_SZ, app_path)
            winreg.CloseKey(key)
        except Exception as e:
            self.status_label.setText(f"设置开机自启动失败: {str(e)}")
 
    def start_timer(self):
        self.timer.stop()
        if self.settings['folder_path']:
            self.timer.start(self.settings['interval'] * 1000)
 
    def change_lockscreen(self):
        if not self.settings['folder_path']:
            return
 
        # 获取文件夹中的所有图片
        valid_extensions = {'.jpg', '.jpeg', '.png', '.bmp'}
        images = [f for f in Path(self.settings['folder_path']).iterdir()
                 if f.suffix.lower() in valid_extensions]
         
        if not images:
            self.status_label.setText("文件夹中没有有效的图片文件")
            return
 
        # 随机选择一张图片
        image_path = str(random.choice(images))
         
        try:
            # 设置锁屏壁纸
            key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                               r'SOFTWARE\Microsoft\Windows\CurrentVersion\PersonalizationCSP',
                               0, winreg.KEY_ALL_ACCESS)
             
            winreg.SetValueEx(key, 'LockScreenImagePath', 0, winreg.REG_SZ,
                             image_path)
            winreg.SetValueEx(key, 'LockScreenImageUrl', 0, winreg.REG_SZ,
                             image_path)
            winreg.SetValueEx(key, 'LockScreenImageStatus', 0, winreg.REG_DWORD, 1)
             
            self.status_label.setText(f"成功更换锁屏壁纸: {Path(image_path).name}")
        except Exception as e:
            self.status_label.setText(f"更换壁纸失败: {str(e)}")
 
def create_executable():
    setup(
        name = "锁屏壁纸更换器",
        version = "1.0",
        description = "Windows锁屏壁纸自动更换程序",
        executables = [Executable("lockscreen_changer.py", base="Win32GUI")],
        options = {
            "build_exe": {
                "packages": ["sys", "os", "json", "PyQt5", "winreg", "win32gui",
                            "win32con", "random", "pathlib"],
            }
        }
    )
 
if __name__ == '__main__':
    if len(sys.argv) > 1 and sys.argv[1] == '--build':
        create_executable()
    else:
        app = QApplication(sys.argv)
        window = LockscreenChanger()
        window.show()
        sys.exit(app.exec_())
 楼主| lx136648 发表于 2025-4-1 15:20
congcongzhidao 发表于 2025-3-31 17:42
[mw_shl_code=python,true]import sys
import os
import json

根本不行,换的是桌面壁纸,而且没有可以选择关闭或开启自启动的按键
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2025-4-4 07:13

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表