使用同一按钮关闭循环并获取屏幕截图以保存在不同的文件夹中

问题描述 投票:0回答:1

顺便说一句,这些点数是为了提醒我 注释是还需要解决的问题 我认为标题和注释概括了我的问题,但我可以在评论中提供帮助 你知道制作按钮的更好方法吗? 以及一种使同一按钮在单击时停止录制的方法 或者录制一个库来代替屏幕截图?

# pip install pyautogui
# pip install opencv-python

# notes
# - get scrrenshots to save to a folder called "screenshots"
# - find a way to stop recording

from tkinter import *

def record():
    import pyautogui as py
    count = 0
        
    while True:
        py.screenshot(str(count) + ".jpg")
        count += 1
    
def turnToVidio():
    import os
    from PIL import Image
    import cv2

    # Get the current working directory
    current_path = os.getcwd()
    print(current_path)

    # Folder containing images
    img_dir = "screenshots"

    def create_video_from_images(folder):
        """Generate a video from all images in the specified folder."""
        video_filename = 'created_video.mp4'
        valid_images = [i for i in os.listdir(folder) if i.endswith((".jpg", ".jpeg", ".png"))]

        first_image = cv2.imread(os.path.join(folder, valid_images[0]))
        h, w, _ = first_image.shape

        codec = cv2.VideoWriter_fourcc(*'mp4v')
        vid_writer = cv2.VideoWriter(video_filename, codec, 30, (w, h))

        for img in valid_images:
            loaded_img = cv2.imread(os.path.join(folder, img))
            for _ in range(20):
                vid_writer.write(loaded_img)

        vid_writer.release()

    def display_video_from_images(folder):
        """Display the video from all images in the specified folder."""
        video_filename = 'created_video.mp4'
        valid_images = [i for i in os.listdir(folder) if i.endswith((".jpg", ".jpeg", ".png"))]

        first_image = cv2.imread(os.path.join(folder, valid_images[0]))
        h, w, _ = first_image.shape

        vid_reader = cv2.VideoCapture(video_filename)

        while True:
            ret, frame = vid_reader.read()
            if not ret:
                # Restart the video when it reaches the end
                vid_reader.set(cv2.CAP_PROP_POS_FRAMES, 0)
                continue
            cv2.imshow("Video", frame)
            if cv2.waitKey(30) & 0xFF == ord('q'):  # Exit when 'q' key is pressed
                break

        vid_reader.release()
        cv2.destroyAllWindows()

    # Create video from resized images
    create_video_from_images(img_dir)

    # Display the video as output
    display_video_from_images(img_dir)

root = Tk()
root.title("Recorder")

mybutton = Button(root,text = "Start/End recording", padx = 50, pady = 50, command = record)
mybutton.pack()
mybutton2 = Button(root,text = "Turn to vidio", padx = 50, pady = 50, command = turnToVidio)
mybutton2.pack()
python file tkinter button pyautogui
1个回答
0
投票

类似这样的:

recording = False
def record():
    global recording
    recording = not recording
    import pyautogui as py
    count = 0
       
    while recording:
        py.screenshot(str(count) + ".jpg")
        count += 1
© www.soinside.com 2019 - 2024. All rights reserved.