Make a smile (PIL create Image and draw on it)

A little funny script about making a smile with PIL (pip install pillow). It is fun, it is simple, but we could start from here to make something more useful and complex (as already done with other examples in this blog). Until now the output will be this:

It will come from this GUI:

At the moment, it is possible to change the color ony within the script, but we are going to add the feature to the app soon.

We want to start keeping the code simple, so this is it:

import tkinter as tk
from PIL import Image
from PIL import ImageDraw
import PIL.Image
import PIL.ImageTk

class Smile:
    def __init__(self, color):
        self.color = color
        self.image = Image.new('RGB', (90, 90), 'white')
        draw = ImageDraw.Draw(self.image)
        draw.ellipse((0, 0, 89, 89), self.color, 'blue')  # made this a little smaller..
        draw.ellipse((25, 20, 35, 30), 'yellow', 'blue')
        draw.ellipse((50, 20, 60, 30), 'yellow', 'blue')
        draw.arc((20, 40, 70, 70), 0, 180, 'black')  # draw anarc in black

    def save(self):
    	self.image.save(self.color + ".png", "PNG")

print("This program creates an image on the fly and shows it in a label of tkinter")

root = tk.Tk()
img = Smile("gold")
orangesmile = PIL.ImageTk.PhotoImage(img.image)
label_title = tk.Label(root, text="Program to create smiles of different colors", font="Arial 20", bg="gold", fg="navy")
label_title.pack()
label = tk.Label(root, image=orangesmile, bd=4)
label.pack()
button_save = tk.Button(root, text="Save", command=img.save)
button_save.pack()

root.mainloop()

Let’s talk about the code

Let’s dive into the code to explain what it does in the main statements.

Create a new image

self.image = Image.new(‘RGB’, (90, 90), ‘white’)

Draw the face

draw = ImageDraw.Draw(self.image)

draw.ellipse((0, 0, 89, 89), self.color, ‘blue’) # made this a little smaller..

draw.ellipse((25, 20, 35, 30), ‘yellow’, ‘blue’)

draw.ellipse((50, 20, 60, 30), ‘yellow’, ‘blue’)

draw.arc((20, 40, 70, 70), 0, 180, ‘black’) # draw anarc in black

Save the image on pc

def save(self):

self.image.save(self.color + “.png”, “PNG”)

The istance of Smile in gold (this runs the app)

img = Smile(“gold”)

Prepare the image to go in the label

orangesmile = PIL.ImageTk.PhotoImage(img.image)

The label that contains the image above

label = tk.Label(root, image=orangesmile, bd=4)

The button to save the image (command=img.save)

button_save = tk.Button(root, text=”Save”, command=img.save)

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.