用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


'''
相关推荐
长安牧笛几秒前
开发农民工技能兼匹配系统,输入技能如水电微修,自动匹配附近需要临时工的家庭或店铺。
python
zew1040994588几秒前
PyCharm【2023.2.5下】中命令行【Terminal】不见了如何解决?
ide·python·pycharm·快捷键·terminal·命令行消失
耶耶耶耶耶~1 分钟前
conan 2.0 Getting Started
python·conan
MarkHD2 分钟前
智能体在车联网中的应用:第12天 CARLA实战:编写Python客户端生成与控制车辆,迈向联合仿真
开发语言·python
Generalzy3 分钟前
应该是跨时代的更新——langgraph v1.0
python
青出于兰3 分钟前
C语言| 指针变量的自增运算
c语言·开发语言
xqqxqxxq5 分钟前
Java 集合框架核心用法与实战技术笔记
java·笔记·python
有味道的男人7 分钟前
Python 爬虫框架设计:类封装与工程化实践
开发语言·爬虫·python
Daily Mirror7 分钟前
Day40 简单 CNN
python
Davina_yu7 分钟前
R语言报错:无法打开文件‘sales_2025.txt‘: No such file or directory
开发语言·r语言