用python实现截屏录屏功能

python 复制代码
# -*-coding:GBK -*-

from datetime import datetime
from PIL import ImageGrab, ImageTk
import cv2
import numpy as np
import threading
import time
import os
import tkinter as tk
from tkinter import messagebox, simpledialog

class ScreenRecorderApp:
    def __init__(self, root):
        self.root = root
        self.root.title("屏幕录制器")
        self.root.geometry("200x150+%d+0" % (root.winfo_screenwidth() - 200))  # 设置窗口位置在右上角
        self.root.configure(bg="#f0f0f0")
        self.root.attributes('-topmost', True)  # 窗口置顶

        self.recording = False
        self.video = None

        self.start_button = tk.Button(root, text="开始录制", command=self.start_recording, bg="#4caf50", fg="white", font=("Arial", 12), activebackground="#45a049")
        self.start_button.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)

        self.stop_button = tk.Button(root, text="停止录制", command=self.stop_recording, state=tk.DISABLED, bg="#f44336", fg="white", font=("Arial", 12), activebackground="#e53935")
        self.stop_button.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)

        self.screenshot_button = tk.Button(root, text="截屏", command=self.take_screenshot, bg="#ff9800", fg="white", font=("Arial", 12), activebackground="#fb8c00")
        self.screenshot_button.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)

    def start_recording(self):
        self.recording = True
        self.start_button.config(state=tk.DISABLED, bg="#a0a0a0")
        self.stop_button.config(state=tk.NORMAL, bg="#f44336")
        self.screenshot_button.config(state=tk.DISABLED)
        self.root.attributes('-alpha', 0.3)  # 提高透明度
        threading.Thread(target=self.record_screen).start()

    def stop_recording(self):
        self.recording = False
        self.start_button.config(state=tk.NORMAL, bg="#4caf50")
        self.stop_button.config(state=tk.DISABLED, bg="#a0a0a0")
        self.screenshot_button.config(state=tk.NORMAL)
        self.root.attributes('-alpha', 1.0)  # 恢复透明度

    def record_screen(self):
        name = datetime.now().strftime("%Y-%m-%d %H-%M-%S")
        screen = ImageGrab.grab()
        width, high = screen.size
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # 修改为MP4格式
        self.video = cv2.VideoWriter(f'{name}.mp4', fourcc, 16, (width, high))
        print("record start !!!")
        while self.recording:
            img = ImageGrab.grab()
            imm = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)  # 转为opencv的BGR模式
            self.video.write(imm)
        print("record end !!!")
        self.video.release()
        time.sleep(1)  # 增加一个短暂的延迟,确保所有帧数据都被写入

        # 检查视频文件是否存在且大小不为零
        if os.path.exists(f'{name}.mp4') and os.path.getsize(f'{name}.mp4') > 0:
            print(f'视频文件 {name}.mp4 已生成')
            messagebox.showinfo("录制完成", f"视频文件 {name}.mp4 已生成")
        else:
            print(f'视频文件 {name}.mp4 未正确生成')
            messagebox.showerror("录制失败", f"视频文件 {name}.mp4 未正确生成")

        # 视频信息
        try:
            video = cv2.VideoCapture(f'{name}.mp4')
            fps = video.get(cv2.CAP_PROP_FPS)
            frames = video.get(cv2.CAP_PROP_FRAME_COUNT)
            if fps == 0 or frames == 0:
                print('视频文件可能未正确生成或为空')
            else:
                print('帧率=%.1f' % (fps))
                print('帧数=%.1f' % (frames))
                print('分辨率=(%d,%d)' % (int(video.get(cv2.CAP_PROP_FRAME_WIDTH)), int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))))
                print('时间=%.2f秒' % (int(frames) / fps))
        except Exception as e:
            print(f'读取视频文件信息时出错: {e}')

    def take_screenshot(self):
        if self.recording:
            messagebox.showwarning("警告", "录制过程中无法截屏")
            return

        self.root.attributes('-alpha', 0.0)  # 完全透明
        screenshot = ImageGrab.grab()
        self.root.attributes('-alpha', 1.0)  # 恢复透明度

        screenshot_name = datetime.now().strftime("%Y-%m-%d %H-%M-%S") + ".png"
        screenshot.save(screenshot_name)
        screenshot.show()
        messagebox.showinfo("截屏完成", f"截屏已保存为 {screenshot_name}")

if __name__ == '__main__':
    root = tk.Tk()
    app = ScreenRecorderApp(root)
    root.mainloop()

'''
# 安装PyInstaller
pip install pyinstaller

# 导航到你的Python脚本所在的目录
cd path/to/your/script

# 使用PyInstaller生成EXE文件
pyinstaller --onefile --windowed record_Screen.py


'''
相关推荐
feiyangqingyun2 小时前
Qt项目作品在苹果macos上编译运行效果/视频监控系统/物联网平台等
开发语言·qt·macos
测试老哥2 小时前
Postman环境变量设置全攻略
自动化测试·软件测试·python·测试工具·职场和发展·接口测试·postman
你不是我我3 小时前
【Java 开发日记】我们来说一说 Redisson 的原理
java·开发语言
kk”3 小时前
C++ stack 和 queue
开发语言·c++
Matlab仿真实验室3 小时前
基于Matlab实现双目图计算深度图
开发语言·数码相机·matlab·双目图计算深度图
惜月_treasure3 小时前
Text2SQL与工作流实现:让数据库查询变得轻松又高效
数据库·人工智能·python
QT 小鲜肉3 小时前
【数据结构与算法基础】05. 栈详解(C++ 实战)
开发语言·数据结构·c++·笔记·学习·算法·学习方法
老K的Java兵器库4 小时前
Collections 工具类 15 个常用方法源码:sort、binarySearch、reverse、shuffle、unmodifiableXxx
java·开发语言·哈希算法
武子康4 小时前
Java-153 深入浅出 MongoDB 全面的适用场景分析与选型指南 场景应用指南
java·开发语言·数据库·mongodb·性能优化·系统架构·nosql
码猩4 小时前
获取dm音视频文案
python