Table of Contents
1. Interface development
2. Screen recording parameter settings
1. Set the screen recording range
2. Mouse event monitoring
3. Keyboard event monitoring
3. Screen recording operation
Home Backend Development Python Tutorial How to implement screen recording function in Python

How to implement screen recording function in Python

May 02, 2023 pm 09:46 PM
python

    1. Interface development

        #设置主界面
    def set_init_window(self):
        # 去掉tkinter默认的标题
        self.tk.title('')
        # 隐藏默认图标
        self.tk.iconbitmap(self.icon_path())
        #获取屏幕的宽度
        screeWidth = self.tk.winfo_screenwidth()
        #获取屏幕高度
        screeHeight = self.tk.winfo_screenheight()
        
        width = int((screeWidth - 500) / 2)
        height = int((screeHeight - 300) / 2)
        # 设置主界面的大小和默认位置
        self.tk.geometry(f'500x100+{width}+{height}')
        
        #添加开始录制按钮,点击之后开启两个线程:一个录屏、一个监听键盘
        btn1 = tkinter.Button(self.tk, width=5, height=1, text='开始',
        command=lambda:[threading.Thread(target=self.video_record).start(),threading.Thread(target=self.start_listen).start()])
        btn1.pack()
        # 设置按钮位置
        btn1.place(x=110, y=50, anchor='n')
        
        #开启新线程设置录屏范围
        btn2 = tkinter.Button(self.tk, width=15, height=1, text='设置录制区域', command=lambda:threading.Thread(target=self.set_range).start())
        btn2.pack()
        btn2.place(x=230, y=50, anchor='n')
    
    
    #生成透明的icon图标
    def icon_path(self):
        ICON = (b'\x00\x00\x01\x00\x01\x00\x10\x10\x00\x00\x01\x00\x08\x00h\x05\x00\x00'
                b'\x16\x00\x00\x00(\x00\x00\x00\x10\x00\x00\x00 \x00\x00\x00\x01\x00'
                b'\x08\x00\x00\x00\x00\x00@\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
                b'\x00\x01\x00\x00\x00\x01') + b'\x00' * 1282 + b'\xff' * 64
        _, ICON_PATH = tempfile.mkstemp()
        with open(ICON_PATH, 'wb') as icon_file:
            icon_file.write(ICON)
        return ICON_PATH
    Copy after login

    2. Screen recording parameter settings

    1. Set the screen recording range

    #设置录屏范围
    def set_range(self):
        #self.init_window.withdraw() #隐藏窗口
        self.tk.state('icon')#窗口最小化
        screeWidth = self.tk.winfo_screenwidth()
        screeHeight = self.tk.winfo_screenheight()
    
        self.newFrame = tkinter.Toplevel(self.tk,width=screeWidth,height=screeHeight,bg='white')#开启新窗口
        self.newFrame.attributes('-transparentcolor', 'white')  # 使白色为透明色
        self.newFrame.overrideredirect(True)  # 隐藏导航栏
    
        self.canvas = tkinter.Canvas(self.newFrame,bg='white',bd=0,width=screeWidth,height=screeHeight)
        self.canvas.bind(&#39;<Button-1>&#39;, self.onLeftButtonDown)#按下左键
        self.canvas.bind(&#39;<B1-Motion>&#39;, self.onLeftButtonMove)#移动鼠标
        self.canvas.bind(&#39;<ButtonRelease-1>&#39;, self.onLeftButtonUp)#抬起左键
        self.canvas.pack(fill=tkinter.BOTH, expand=tkinter.YES)
    
        time.sleep(0.3)
        im = ImageGrab.grab()
        # 暂存全屏截图
        im.save(&#39;temp.png&#39;)
        im.close()
        self.image = tkinter.PhotoImage(file=&#39;temp.png&#39;)
        os.remove(&#39;temp.png&#39;)
        self.canvas.create_image(screeWidth//2, screeHeight//2, image=self.image)
    Copy after login

    2. Mouse event monitoring

    #按下鼠标
    def onLeftButtonDown(self,event):
        try:
            self.canvas.delete(self.lastDraw)
            self.canvas.delete(self.dot1)
            self.canvas.delete(self.dot2)
            self.btn3.destroy()
        except Exception as e:
            pass
    
        self.X = event.x
        self.Y = event.y
        self.X2 = 0
        self.Y2 = 0
    
    #移动鼠标
    def onLeftButtonMove(self,event):
        try:  # 删除刚画完的图形,不然所有画的框都会出现
            self.canvas.delete(self.lastDraw)
            self.canvas.delete(self.dot1)
            self.canvas.delete(self.dot2)
            self.btn3.destroy()
        except Exception as e:
            pass
    
        self.X2 = event.x
        self.Y2 = event.y
        self.lastDraw = self.canvas.create_rectangle(self.X, self.Y, event.x, event.y,width=2, outline=&#39;pink&#39;)
    
    #松开鼠标
    def onLeftButtonUp(self,event):
        print("起点", self.X, self.Y)
        print("终点", self.X2, self.Y2)
    
        if self.X2==0 and self.X2==0:
            return
    
        self.width, self.high = self.X2-self.X,self.Y2-self.Y
        self.region = (self.X, self.Y, self.X2, self.Y2)
    
        self.dot1=self.canvas.create_text(self.X, self.Y - 10, text=f&#39;({self.X},{self.Y})&#39;, font=("Purisa", 12), fill="pink")
        self.dot2=self.canvas.create_text(self.X2, self.Y2 + 10, text=f&#39;({self.X2},{self.Y2})&#39;, font=("Purisa", 12), fill="pink")
    
        # self.newFrame.destroy()#销毁窗口
        # self.init_window.deiconify()#显示窗口
        # self.tk.state(&#39;normal&#39;)  # 取消窗口最小化
    
        self.btn3 = tkinter.Button(self.canvas, width=15, height=1, text=&#39;确定录制区域&#39;,bg=&#39;pink&#39;,fg=&#39;#64854c&#39;,command=lambda:[self.newFrame.destroy(),self.tk.state(&#39;normal&#39;)])
        self.btn3.pack()
        self.btn3.place(x=self.X2-20, y=self.Y2+20, anchor=&#39;n&#39;)
    Copy after login

    3. Keyboard event monitoring

    # 开始监听
    def start_listen(self):
        with keyboard.Listener(on_press=self.on_press) as listener:
            listener.join()
        # 监听按键
    def on_press(self,key):
        if key == keyboard.Key.esc:
            self.flag = True  # 改变
            return False  # 返回False,键盘监听结束!
    Copy after login

    3. Screen recording operation

    def video_record(self):
         fourcc = cv2.VideoWriter_fourcc(&#39;X&#39;, &#39;V&#39;, &#39;I&#39;, &#39;D&#39;)
         out = cv2.VideoWriter(&#39;output.mp4&#39;, fourcc, 14, (self.width, self.high))  # 参数分别为 输出文件名,解码方式,帧数,录像范围
         self.count = 1
         while (True):
             img = ImageGrab.grab(self.region) #指定截取坐标(左边X,上边Y,右边X,下边Y)
             img_np = numpy.array(img)
             frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)  # ImageGrab获取的颜色为BGR排序,需转换为RGB
             out.write(frame)
             self.count += 1
             label = tkinter.Label(self.tk, text=f"{int(self.count / 14)}秒")
             label.pack()
             label.place(x=320, y=55, anchor=&#39;n&#39;)
             # 点击ESC退出
             if self.flag == True:
                 tkinter.messagebox.showinfo(&#39;提示&#39;, &#39;录屏结束&#39;)
                 self.flag = False  # 改变录屏状态
                 break
         out.release()
         cv2.destroyAllWindows()
    Copy after login

    The above is the detailed content of How to implement screen recording function in Python. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Hot Topics

    Java Tutorial
    1664
    14
    PHP Tutorial
    1268
    29
    C# Tutorial
    1243
    24
    PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

    PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

    Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

    PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

    PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

    PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

    Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

    Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

    How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

    To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

    Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

    Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

    Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

    Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

    How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

    Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

    See all articles