How to take screenshot in pygame

We can take screenshot in pygame with

pygame.image.save(screen, “screenshot.png”)

And this is the example program for this

If we directly add this in the pygame loop that will continuously take the screenshot. To solve this we will add a button so when the user click the button the program will take the screenshot. This more efficient solution

for event in pygame.event.get():
    if event.type == QUIT:
        pygame.quit()
        sys.exit()
    elif event.type == MOUSEBUTTONDOWN:
        mouse_pos = pygame.mouse.get_pos()
        if button_rect.collidepoint(mouse_pos):
            #When the button clicked it will save the screenshot
            pygame.image.save(screen, "screenshot.png")

The complete code




import pygame
import sys
from pygame.locals import *
import datetime
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((400, 400), RESIZABLE)


White = (255,255,255)
SeaGreen = (46, 139, 87)
Green = (0, 128, 0)

def draw_button(surface, text='button', font=None, font_color=White, bg_color=SeaGreen, position=(0, 0), size=(150, 40)):
	button_surface = pygame.Surface(size)
	button_surface.fill(bg_color)
	
	if font is None:
		font = pygame.font.Font(None, 22)
	text_render = font.render(text, True, font_color)
	text_rect = text_render.get_rect(center=(size[0] / 2, size[1] / 2))
	button_surface.blit(text_render, text_rect)
	
	rect = surface.blit(button_surface, position)
	
	return rect

game_running = True
while game_running:
	clock.tick(60)
	screen.fill(White)
	

	for i in range(1, 5):
		for j in range(1, 5):
			pygame.draw.rect(screen, SeaGreen, (i * 60, j * 60, 50, 50), border_radius=10)
			pygame.draw.rect(screen, Green, (i * 60, j * 60, 50, 50), 5, border_radius=10)
	

	button_rect = draw_button(screen, "Take Screenshot", position=(100, 320))


	pygame.display.update()
	

	for event in pygame.event.get():
		if event.type == QUIT:
			pygame.quit()
			sys.exit()
		elif event.type == MOUSEBUTTONDOWN:
			mouse_pos = pygame.mouse.get_pos()
			if button_rect.collidepoint(mouse_pos):
				current_datetime = datetime.datetime.now()
				current_time = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
				#When the button clicked it will save the screenshot
				#pygame.image.save(screen, "screenshot.png")
				pygame.image.save(screen, f"screenshot_{current_time}.png") 

				#print("Screenshot saved as screenshot.png")
				print(f"Screenshot saved as screenshot_{current_time}.png")
	





More Things we can do with pygame screenshot!

Can we take screenshot on a specific time?

Yes we can. We just have to add this logic. Import dateime module if have not already imported

current_time = datetime.datetime.now().strftime("%H:%M")
if current_time == "10:00":
	pygame.image.save(screen, "screenshot.png")

Add this code this in the while loop after pygame.display.update() .

The code check if the current time is equal to our preset time. And take the screenshot on that time.

Can we take screen with time duration for example 2 second after the button click Or specific game event?

Of course!

In pygame we can add custom event to achieve this . Heres the example code



import pygame
import sys
from pygame.locals import *


pygame.init()

screen = pygame.display.set_mode((400, 400))

clock = pygame.time.Clock()

TAKE_SCREENSHOT = pygame.USEREVENT + 1

running = True
while running:
	screen.fill((0,200,0))
	for event in pygame.event.get():
		if event.type == QUIT:
			pygame.quit()
			sys.exit()


		elif event.type == KEYDOWN:
			if event.key == K_SPACE:
				# Schedule taking a screenshot event after 2 seconds
				pygame.time.set_timer(TAKE_SCREENSHOT, 2000)  # 2000 milliseconds = 2 seconds
		elif event.type == TAKE_SCREENSHOT:
			pygame.image.save(screen, "screenshot.png")
			print("Screenshot saved")
			# Stop the timer
			pygame.time.set_timer(TAKE_SCREENSHOT, 0)

	pygame.display.update()
	clock.tick(60)




Where we need to apply the screenshot

For example when the game over we can show the users screenshot of the last checkpoint of that game. The best thing is we can take sequence of screenshot and make that motion gif pictures. That will be more fun and interactive for the game player.

If you are interested in more pygame examples you can get 50+ pygame examples from github

Related Posts

Send Desktop notification from pygame
April 29, 2024

For notification handling we will use plyer library We will add this functionality in our pygame code The complete code import pygame import sys from pygame.locals import * from plyer import notification pygame.init() clock = pygame.time.Clock() user_display = pygame.display.Info() width, height = 800, 600 screen = pygame.display.set_mode((width, height)) background = (255, 255, 255) red = […]

Pygame Project: Create the simplest digital clock
April 28, 2024

We will use python datetime module for our clock; We get the current time and separate the time into hour minutes and second. First get the current time Get the time in hour, minute and second Now got our clock time components. It will be like this import datetime current_time = datetime.datetime.now() hour = current_time.hour […]

Simulate Bird Flocking Behavior with pygame: Algorithm and Code Explained
March 23, 2024

Bird flocking is a wonderful example of how simple behaviors can lead to complex, beautiful patterns in nature. We’ll learn the key principles behind this flocking behavior and write a python program to simulate this wonderful phenomenon. The principles Bird Flocking Simulation Algorithm Setting Up the Simulation Each Frame of the Simulation The pygame example […]