How to get a part of the screen image with Pygame (v. 3)

In this new version of pygame now the screen become opaque at start and when you click the first time on the top left of the part of the screen you want to grab it will form a rectangle when you move the mouse so that you can see what is the part that you will grab. Now the script is quite similar to the snippet tool of windows 11 (that won’t work to me at the moment, I had to get back the old snippet tool from window 10).

(new version)

# grabscreen.py

import pyscreenshot as ImageGrab
import os
from PIL import Image
from io import BytesIO
import win32clipboard
import pygame
import win32api
import win32con
import win32gui
import tkinter as tk


def destroy():
    root.destroy()

root = tk.Tk()
b = tk.Button(root, text="Click to Capture screen",
    fg='red',
    bg='yellow',
    font="Arial 36",
    command=root.destroy)
b.pack()
root.mainloop()


def preview():
    root = tk.Tk()
    image = tk.PhotoImage(file="im.png")
    b = tk.Label(root, image=image,
        fg='red',
        bg='yellow',
        font="Arial 36")
    b.pack()
    root.mainloop()


def send_to_clipboard(clip_type, data):
    win32clipboard.OpenClipboard()
    win32clipboard.EmptyClipboard()
    win32clipboard.SetClipboardData(clip_type, data)
    win32clipboard.CloseClipboard()

def grab(x, y, w, h):
    im = ImageGrab.grab(bbox=(x, y, w, h))
    im.save('im.png')
    image = Image.open("im.png")
    output = BytesIO()
    image.convert("RGB").save(output, "BMP")
    data = output.getvalue()[14:]
    output.close()
    send_to_clipboard(win32clipboard.CF_DIB, data)

pygame.init()
info = pygame.display.Info()
w = info.current_w
h = info.current_h
screen = pygame.display.set_mode((w, h), pygame.NOFRAME) # For borderless, use pygame.NOFRAME
done = False
fuchsia = (255, 0, 128)  # Transparency color

# Create layered window
hwnd = pygame.display.get_wm_info()["window"]
win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE,
                       win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) | win32con.WS_EX_LAYERED)
# Set window transparency color
# win32gui.SetLayeredWindowAttributes(hwnd, win32api.RGB(*fuchsia), 0, win32con.LWA_COLORKEY)
win32gui.SetLayeredWindowAttributes(hwnd, win32api.RGB(*fuchsia), 50, win32con.LWA_ALPHA)

click1 = 0
x1 = 0
y1 = 0
x2 = 0
y2 = 0
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                done = True

        if event.type == pygame.MOUSEBUTTONDOWN:
            # time.sleep(.1)
            if click1 == 0:
                x1, y1 = pygame.mouse.get_pos()
                click1 = 1
            elif click1 == 1:
                x2, y2 = pygame.mouse.get_pos()
                dx = x1 + (x2 - x1)
                dy = y1 + (y2 - y1)
                win32gui.SetLayeredWindowAttributes(hwnd, win32api.RGB(*fuchsia), 0, win32con.LWA_ALPHA)
                grab(x1, y1, dx, dy)
                click1 = 0
                # Sh
                # done = True
                win32gui.SetLayeredWindowAttributes(hwnd, win32api.RGB(*fuchsia), 50, win32con.LWA_ALPHA)
                x1 = 0
                y1 = 0
                x2 = 0
                y2 = 0
                preview()

    screen.fill((255, 255, 255))  # Transparent background
    # show_text()
    if click1 == 0:
        mx, my = pygame.mouse.get_pos()
        dx = 5
        dy = 5
    elif click1 == 1:
        mx2, my2 = pygame.mouse.get_pos()
        x2 = mx2 - x1
        y2 = my2 - y1

    pygame.draw.rect(screen, (0, 255, 255), pygame.Rect(mx, my, x2, y2))
    pygame.display.update()

pygame.quit()

See the capture screen in action

I’ve updated the code, now you can see what you have captured in a tkinter window and you can also get other images, because it does not close itself immediately. Press Esc to close the program.

A live stream with the new feature to see the preview of the captured image

Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.