如何使用Python做个自定义动态壁纸

时间:2022-10-30 18:47:59

使用python做个自定义动态壁纸

首先一起来看看最终实现的自定义动态壁纸效果:

如何使用Python做个自定义动态壁纸接我

接下来,我们开始介绍这个自定义动态桌面的制作过程。

一、核心功能设计

总体来说,我们需要实现将自己喜欢的视频转成一个动态桌面,知识点主要包含了对视频提取解析视频轮播pyqt5窗体设置桌面句柄获取自定义动态桌面壁纸实现等。

大致可以整理出我们需要分为以下几步完成:

  1. ui排版布局设计,确认动态壁纸功能设计
  2. 加载视频,对视频进行预览读取,保存视频路径等
  3. 动态壁纸功能实现应用,获取桌面句柄,轮播加载视频
  4. 关闭动态壁纸,在线壁纸资源获取等

二、实现步骤

之前有粉丝反馈说,想自己跟着文章自己敲敲代码,但是不知道具体需要哪些模块、包文件,后面我就把所有用到模块先放出来。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import os
import sys
from subprocess import call
from threading import thread
from time import sleep
 
import cv2
from pyqt5 import qtcore,  qtwidgets
from pyqt5.qtcore import qt,  qtimer
from pyqt5.qtgui import qimage, qpixmap, qicon
 
from pyqt5.qtwidgets import qgridlayout, qpushbutton, qmainwindow, qfiledialog, qlabel, qsystemtrayicon, \
    qaction, qmenu, qmessagebox
from os import path as pathq

1. ui排版布局设计

根据动态壁纸所需要的功能,首先进行ui布局设计,我们这次还是使用的pyqt5。主要包含了加载读取本地视频、视频加载预览、动态壁纸应用、动态壁纸关闭等。核心设计代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# author:服务器之家
def setupui(self, mainwindow):
    mainwindow.setobjectname("mainwindow")
    mainwindow.resize(505, 615)
    mainwindow.settoolbuttonstyle(qtcore.qt.toolbuttonicononly)
    self.centralwidget = qtwidgets.qwidget(mainwindow)
    self.centralwidget.setobjectname("centralwidget")
    self.pushbutton = qtwidgets.qpushbutton(self.centralwidget)
    self.pushbutton.setgeometry(qtcore.qrect(22, 10, 89, 31))
    self.pushbutton.setobjectname("pushbutton")
    self.pushbutton.clicked.connect(self.openmp4)
    self.pushbutton.setstylesheet(
        '''qpushbutton{background:#f7d674;border-radius:5px;}qpushbutton:hover{background:yellow;}''')
    self.groupbox = qtwidgets.qgroupbox(self.centralwidget)
    self.groupbox.setgeometry(qtcore.qrect(22, 50, 452, 351))
    self.groupbox.setobjectname("groupbox")
    self.widget = qtwidgets.qwidget(self.groupbox)
    self.widget.setgeometry(qtcore.qrect(11, 20, 430, 291))
    self.widget.setobjectname("widget")
    self.gridlayout_3 = qtwidgets.qgridlayout(self.widget)
    self.gridlayout_3.setobjectname("gridlayout_3")
    self.label = qlabel(self)
    self.label.resize(400, 300)
    self.label.settext("waiting for video...")
    self.gridlayout_3.addwidget(self.label)
    self.close_widget = qtwidgets.qwidget(self.centralwidget)
    self.close_widget.setgeometry(qtcore.qrect(420, 0, 93, 41))
    self.close_widget.setobjectname("close_widget")
    self.close_layout = qgridlayout()  # 创建左侧部件的网格布局层
    self.close_widget.setlayout(self.close_layout)  # 设置左侧部件布局为网格
    self.left_close = qpushbutton("")  # 关闭按钮
    self.left_close.clicked.connect(self.close)
    self.left_visit = qpushbutton("")  # 空白按钮
    #self.left_visit.clicked.connect(mainwindow.big)
    self.left_mini = qpushbutton("")  # 最小化按钮
    self.left_mini.clicked.connect(mainwindow.mini)
    self.close_layout.addwidget(self.left_mini, 0, 0, 1, 1)
    self.close_layout.addwidget(self.left_close, 0, 2, 1, 1)
    self.close_layout.addwidget(self.left_visit, 0, 1, 1, 1)
    self.left_close.setfixedsize(15, 15# 设置关闭按钮的大小
    self.left_visit.setfixedsize(15, 15# 设置按钮大小
    self.left_mini.setfixedsize(15, 15# 设置最小化按钮大小
    self.left_close.setstylesheet(
        '''qpushbutton{background:#f76677;border-radius:5px;}qpushbutton:hover{background:red;}''')
    self.left_visit.setstylesheet(
        '''qpushbutton{background:#f7d674;border-radius:5px;}qpushbutton:hover{background:yellow;}''')
    self.left_mini.setstylesheet(
        '''qpushbutton{background:#6ddf6d;border-radius:5px;}qpushbutton:hover{background:green;}''')
    self.horizontallayout = qtwidgets.qhboxlayout(self.close_widget)
    self.horizontallayout.setcontentsmargins(0, 0, 0, 0)
    self.horizontallayout.setobjectname("horizontallayout")
    self.pushbutton_2 = qtwidgets.qpushbutton(self.centralwidget)
    self.pushbutton_2.setgeometry(qtcore.qrect(77, 440, 133, 41))
    self.pushbutton_2.setobjectname("pushbutton_2")
    self.pushbutton_2.clicked.connect(self.play)
    self.pushbutton_2.setstylesheet(
        '''qpushbutton{background:#6ddf6d;border-radius:5px;}qpushbutton:hover{background:green;}''')
    self.pushbutton_3 = qtwidgets.qpushbutton(self.centralwidget)
    self.pushbutton_3.setgeometry(qtcore.qrect(308, 440, 111, 41))
    self.pushbutton_3.setobjectname("pushbutton_3")
    self.pushbutton_3.clicked.connect(self.close_wall)
    self.pushbutton_3.setstylesheet(
        '''qpushbutton{background:#f76677;border-radius:5px;}qpushbutton:hover{background:red;}''')
    self.pushbutton_4 = qtwidgets.qpushbutton(self.centralwidget)
    self.pushbutton_4.setgeometry(qtcore.qrect(187, 540, 133, 21))
    self.pushbutton_4.setobjectname("pushbutton_4")
    self.pushbutton_4.clicked.connect(self.openurl)
    self.pushbutton_4.setstylesheet(
        '''qpushbutton{background:#222225;color:white;border-radius:5px;}qpushbutton:hover{background:#222225;color:skyblue}''')
    mainwindow.setcentralwidget(self.centralwidget)
    self.menubar = qtwidgets.qmenubar(mainwindow)
    self.menubar.setgeometry(qtcore.qrect(0, 0, 505, 23))
    self.menubar.setobjectname("menubar")
    mainwindow.setmenubar(self.menubar)
    self.statusbar = qtwidgets.qstatusbar(mainwindow)
    self.statusbar.setobjectname("statusbar")
    mainwindow.setstatusbar(self.statusbar)
    self.retranslateui(mainwindow)
    qtcore.qmetaobject.connectslotsbyname(mainwindow)
    self.groupbox.setstylesheet('''
    color:white
    ''')
    mainwindow.setwindowopacity(0.95# 设置窗口透明度
    mainwindow.setattribute(qt.wa_translucentbackground)
    mainwindow.setwindowflag(qt.framelesswindowhint)  # 隐藏边框
# author:服务器之家
def retranslateui(self, mainwindow):
    _translate = qtcore.qcoreapplication.translate
    mainwindow.setwindowtitle(_translate("mainwindow", "mainwindow"))
    self.pushbutton.settext(_translate("mainwindow", "从本地选择"))
    self.groupbox.settitle(_translate("mainwindow", "预览"))
    self.pushbutton_2.settext(_translate("mainwindow", "应用"))
    self.pushbutton_3.settext(_translate("mainwindow", "关闭壁纸"))
    self.pushbutton_4.settext(_translate("mainwindow", "在线资源"))

ui实现效果如下:

如何使用Python做个自定义动态壁纸

ui布局设计完成,下面我们开始进行视频读取加载、预览功能实现。

2. 视频加载预览

接来下我们可以根据自己喜欢的视频,从本地读取视频,并且将视频预览播放显示。这里视频演示,博主还是用之前的那篇紫颜小姐姐的跳舞视频进行演示。

读取视频:

读取视频我们可以通过打开文件对话框,选择视频资源,开启一个子线程用来进行视频开启停止播放。核心代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# author:服务器之家
def openmp4(self):
    try:
        global path
        path, filetype = qfiledialog.getopenfilename(none, "选择文件", '.',
                                                     "视频文件(*.avi;*.mov;*.rmvb;*.rm;*.flv;*.mp4;*.3gp)"# ;;all files (*)
        if path == "":  # 未选择文件
            return
 
        self.slotstart()
        t = thread(target=self.stop)
        t.start()  # 启动线程,即让线程开始执行
    except exception as e:
        print (e)

视频流读取播放:

接下来,我们需要对视频文件进行按帧读取加载显示,并通过计时器实现动画效果。核心代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# author:服务器之家
def slotstart(self):
    videoname = path
    if videoname != "":  # “”为用户取消
        self.cap = cv2.videocapture(videoname)
        self.timer_camera.start(50)
        self.timer_camera.timeout.connect(self.openframe)
 
# author:服务器之家
def openframe(self):
    if (self.cap.isopened()):
        ret, self.frame = self.cap.read()
        if ret:
            frame = cv2.cvtcolor(self.frame, cv2.color_bgr2rgb)
            if self.detectflag == true:
                # 检测代码self.frame
                self.label_num.settext("there are " + str(5) + " people.")
            height, width, bytespercomponent = frame.shape
            bytesperline = bytespercomponent * width
            q_image = qimage(frame.data, width, height, bytesperline,
                             qimage.format_rgb888).scaled(self.label.width(), self.label.height())
            self.label.setpixmap(qpixmap.fromimage(q_image))
        else:
            self.cap.release()
            self.timer_camera.stop()  # 停止计时器

至此,我们已经可以实现视频读取加载,并且进行视频预览了,效果如下:

如何使用Python做个自定义动态壁纸

3. 动态壁纸功能实现

实现桌面壁纸替换,我们首先需要获取桌面句柄找到桌面窗体,覆写桌面窗体、调用加载的视频流,播放动态壁纸。

获取桌面句柄:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# author:服务器之家
def pretreatmenthandle():
    hwnd = win32gui.findwindow("progman", "program manager")
    win32gui.sendmessagetimeout(hwnd, 0x052c, 0, none, 0, 0x03e8)
    hwnd_workw = none
    while 1:
        hwnd_workw = win32gui.findwindowex(none, hwnd_workw, "workerw", none)
        if not hwnd_workw:
            continue
        hview = win32gui.findwindowex(hwnd_workw, none, "shelldll_defview", none)
        # print('hwmd_hview: ', hview)
        if not hview:
            continue
        h = win32gui.findwindowex(none, hwnd_workw, "workerw", none)
        while h:
            win32gui.sendmessage(h, 0x0010, 0, 0# wm_close
            h = win32gui.findwindowex(none, hwnd_workw, "workerw", none)
        break
    return hwnd

桌面覆写:

我们可以创建一个类,对窗体进行继承,进行视频流加载读取播放。核心代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# author:服务器之家
class mymainwindow(qmainwindow, ui_mainwindow):
    def __init__(self, parent=none):
        super(mymainwindow, self).__init__(parent)
        self.ui = ui_mainwindow()
        self.ui.setupui(self)
        self.player = qmediaplayer()
        self.player.setnotifyinterval(10000)
        self.player.setvideooutput(self.ui.videowidget)
        self.player.setmuted(bool(1 - self.player.ismuted()))
        self.setwindowflags(qt.framelesswindowhint)
        self.setupui(self)
        self.go()
 
 
 # author: 服务器之家
    def go(self):
        self.ui.videowidget.setfullscreen(true)
 
        with open("./filename.txt", 'r', encoding='utf-8') as f:
            file_name = f.read()
            if file_name =='':
                file_name = 'lkf.mp4'
        print (file_name)
        if not os.path.exists(file_name):
            sys.exit()
        media = qmediacontent(qurl(file_name))
        self.player.setmedia(media)
        self.mplaylist = qmediaplaylist()
        self.mplaylist.addmedia(qmediacontent(qurl.fromlocalfile(file_name)))
        self.player.setplaylist(self.mplaylist)
        self.mplaylist.setplaybackmode(qmediaplaylist.currentiteminloop)
        win_hwnd = int(self.winid())
        video_h = int(self.ui.videowidget.winid())
        win32gui.setparent(win_hwnd, h)
        win32gui.setparent(video_h, h)
        win32gui.setparent(video_h, win_hwnd)
        self.player.play()

这里我们把上面的py文件直接打包成exe文件,接下来我们在“应用”控件上进行事件绑定,直接调用exe执行,实现动态壁纸播放应用功能。核心代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def play(self):
     if path == '':
         reply = qtwidgets.qmessagebox.question(self, '提示',
                                                "未加载选择视频",
                                                qtwidgets.qmessagebox.yes)
         return
     with open("./filename.txt", 'w', encoding='utf-8') as f:
         f.truncate(0)
         print(f.write(str(path)))
     try:
         try:
             call('taskkill /f /im play.exe')
         except:
             pass
         os.system('start play.exe')
     except:
         pass
     try:
         if self.cap != []:
             self.cap.release()
             self.timer_camera.stop()  # 停止计时器
         else:
             warming = qmessagebox.warning(self, "warming", "push the left upper corner button to quit.",
                                           qmessagebox.yes)
     except:
         pass

这样,我们就完成了动态壁纸加载应用功能了,效果如下:

如何使用Python做个自定义动态壁纸

4. 关闭动态壁纸

最后我们再实现下当前动态壁纸播放关闭功能,我们需要对当前桌面视频播放进行释放取消。代码如下:

?
1
2
3
4
5
6
# author:服务器之家
 def close_wall(self):
     try:
         call('taskkill /f /im play.exe')
     except:
         pass

效果如下:

如何使用Python做个自定义动态壁纸

至此,整个自定义动态桌面壁纸功能就全部完成了,下面我们一起运行下看看动态壁纸效果。

到此这篇关于使用python做个自定义动态壁纸的文章就介绍到这了,更多相关python做动态壁纸内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/hhladminhhl/article/details/119902562