PyGameGif – Draw GIF with Pygame

Let’s add some colors to the app to draw on the screen… we had this code, posted some time ago.

The very basic window that just draws

from PIL import Image
# pip install pillow
import pygame
import glob
import os

pygame.init()
# create the window
screen = pygame.display.set_mode((600,400))
# give the name to the window
pygame.display.set_caption("Trace")
clock = pygame.time.Clock()

loop = 1
while loop:
	try:
		for event in pygame.event.get():
			if event.type== pygame.QUIT:
				loop = False
		px, py = pygame.mouse.get_pos()
		if pygame.mouse.get_pressed() == (1,0,0):
			pygame.draw.ellipse(screen, (255,255,255), (px,py,10,10))
		pygame.display.update()
		clock.tick(100)

	except Exception as e:
		print(e)
		pygame.quit()

pygame.quit()

There is the following code that adds more features like deleting and saving images and even making gifs of the diffent images saved…

The code to delete, save and make gifs out of the drawings

With not many more lines we added a lot of features to the app: deleting all the image, deleting part of the drawing with the right button of the mouse, saving screen and making animated gifs pressing g, after having saved multiple images.

from PIL import Image
import pygame
import glob
import os

pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Trace")
clock = pygame.time.Clock()

loop = True
press = False
color = "white"
cnt = 0
[os.remove(png) for png in glob.glob("*png")]
while loop:
    try:
        #pygame.mouse.set_visible(False)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                loop = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_d:
                    screen.fill(pygame.Color(0, 0, 0))
                if event.key == pygame.K_s:
                    if cnt < 10:
                        pygame.image.save(screen, f"screenshot0{cnt}.png")
                    else:
                        pygame.image.save(screen, f"screenshot{cnt}.png")
                    cnt += 1
                if event.key == pygame.K_g:
                        frames = []
                        imgs = glob.glob("*.png")
                        for i in imgs:
                            new_frame = Image.open(i)
                            frames.append(new_frame)

                        # Save into a GIF file that loops forever
                        frames[0].save('animated.gif', format='GIF',
                                       append_images=frames[1:],
                                       save_all=True,
                                       duration=300, loop=0)
                        os.startfile("animated.gif")

    
        px, py = pygame.mouse.get_pos()
        if pygame.mouse.get_pressed() == (1,0,0):
            pygame.draw.ellipse(screen, (255,255,255), (px,py,10,10))
        if pygame.mouse.get_pressed() == (0,0,1):
            pygame.draw.rect(screen, (0,0,0), (px,py,10,10))

        if event.type == pygame.MOUSEBUTTONUP:
            press == False
        pygame.display.update()
        clock.tick(100)
    except Exception as e:
        print(e)
        pygame.quit()
        
pygame.quit()

Finally, some colors

Just draw in white is good for basi backboard teaching stuff, but why do not add some colors to enhance the experience? That’s the code:

from PIL import Image
import pygame
import glob
import os
from random import choice

pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Trace")
clock = pygame.time.Clock()

loop = True
press = False
color = "white"
cnt = 0
[os.remove(png) for png in glob.glob("*png")]
blue = (0,0,255)
yellow = (0,255,0)
red = (255,0,0)
color = (255,255,255)
while loop:
    try:
        #pygame.mouse.set_visible(False)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                loop = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_b:
                    color = blue
                if event.key == pygame.K_y:
                    color = yellow
                if event.key == pygame.K_r:
                    color = red
                if event.key == pygame.K_w:
                    color = (255,255,255)
                if event.key == pygame.K_d:
                    screen.fill(pygame.Color(0, 0, 0))
                if event.key == pygame.K_s:
                    if cnt < 10:
                        pygame.image.save(screen, f"screenshot0{cnt}.png")
                    else:
                        pygame.image.save(screen, f"screenshot{cnt}.png")
                    cnt += 1
                if event.key == pygame.K_g:
                        frames = []
                        imgs = glob.glob("*.png")
                        for i in imgs:
                            new_frame = Image.open(i)
                            frames.append(new_frame)

                        # Save into a GIF file that loops forever
                        frames[0].save('animated.gif', format='GIF',
                                       append_images=frames[1:],
                                       save_all=True,
                                       duration=300, loop=0)
                        os.startfile("animated.gif")

    
        px, py = pygame.mouse.get_pos()
        if pygame.mouse.get_pressed() == (1,0,0):
            pygame.draw.ellipse(screen, color, (px,py,10,10))
        if pygame.mouse.get_pressed() == (0,0,1):
            pygame.draw.rect(screen, (0,0,0), (px,py,10,10))

        if event.type == pygame.MOUSEBUTTONUP:
            press == False
        pygame.display.update()
        clock.tick(100)
    except Exception as e:
        print(e)
        pygame.quit()
        
pygame.quit()

And this is one of the output

Adding a message box with shortcuts

Let’s use tkinter to show a message with the shortcuts keys

import tkinter as tk
from tkinter import messagebox

After we imported tkinter and messagebox…

                if event.key == pygame.K_h:
                    root = tk.Tk()
                    root.withdraw()
                    messagebox.showinfo("Help","Press b, y or r w for colors\nd for delete\ns to save screen and g to make a gif")

we add the above code to the list of event in the while loop

The whole code

from PIL import Image
import pygame
import glob
import os
from random import choice
import tkinter as tk
from tkinter import messagebox

pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("PyDraw - Press h for help")
clock = pygame.time.Clock()

loop = True
press = False
color = "white"
cnt = 0
[os.remove(png) for png in glob.glob("*png")]
blue = (0,0,255)
yellow = (0,255,0)
red = (255,0,0)
color = (255,255,255)
while loop:
    try:
        #pygame.mouse.set_visible(False)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                loop = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_b:
                    color = blue
                if event.key == pygame.K_y:
                    color = yellow
                if event.key == pygame.K_h:
                    root = tk.Tk()
                    root.withdraw()
                    messagebox.showinfo("Help","Press b, y or r w for colors\nd for delete\ns to save screen and g to make a gif")
                if event.key == pygame.K_r:
                    color = red
                if event.key == pygame.K_w:
                    color = (255,255,255)
                if event.key == pygame.K_d:
                    screen.fill(pygame.Color(0, 0, 0))
                if event.key == pygame.K_s:
                    if cnt < 10:
                        pygame.image.save(screen, f"screenshot0{cnt}.png")
                    else:
                        pygame.image.save(screen, f"screenshot{cnt}.png")
                    cnt += 1
                if event.key == pygame.K_g:
                        frames = []
                        imgs = glob.glob("*.png")
                        for i in imgs:
                            new_frame = Image.open(i)
                            frames.append(new_frame)

                        # Save into a GIF file that loops forever
                        frames[0].save('animated.gif', format='GIF',
                                       append_images=frames[1:],
                                       save_all=True,
                                       duration=300, loop=0)
                        os.startfile("animated.gif")

    
        px, py = pygame.mouse.get_pos()
        if pygame.mouse.get_pressed() == (1,0,0):
            pygame.draw.ellipse(screen, color, (px,py,10,10))
        if pygame.mouse.get_pressed() == (0,0,1):
            pygame.draw.rect(screen, (0,0,0), (px,py,10,10))

        if event.type == pygame.MOUSEBUTTONUP:
            press == False
        pygame.display.update()
        clock.tick(100)
    except Exception as e:
        print(e)
        pygame.quit()
        
pygame.quit()

Now you do not have to remember all the keys.

… and this is how it looks like when you press ‘h’…

This draw app on repl.it

Go to this link to try this app online

To be continued…

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.