In this video I’ll show you how to add text to images programatically using the Pillow Library with Tkinter and Python.

We’ve used PIL lots of times in the playlist…in this video we’ll use it to add text to images.

We’ll create an entry box that we can type text into, and a button to press that will save the text on the image.

Python Code: picture_text.py
(Github Code)

from tkinter import *
from PIL import Image, ImageFont, ImageDraw


root = Tk()
root.title('Codemy.com - Add Text To Images')
root.iconbitmap('c:/gui/codemy.ico')
root.geometry("600x650")

# Add Text To Image
def add_it():
	# Open our image
	my_image = Image.open("images/aspen.png")
	# Define The Font
	text_font = ImageFont.truetype("arial.ttf", 46)
	# Get text to add to image
	text_to_add = my_entry.get()

	# Edit the Image
	edit_image = ImageDraw.Draw(my_image)
	edit_image.text((150, 300), text_to_add, ("green"), font=text_font)
	
	# Save The Image
	my_image.save("images/aspen2.png")

	# Clear the entry box
	my_entry.delete(0, END)
	my_entry.insert(0, "Saving File...")

	# Wait a couple seconds and then show image
	my_label.after(2000, show_pic)

def show_pic():
	# Show New Image
	global aspen2
	aspen2 = PhotoImage(file="images/aspen2.png")
	my_label.config(image=aspen2)

	# Clear the entry box 
	my_entry.delete(0, END)



# Define Image
aspen = PhotoImage(file="images/aspen.png")

# Create A Label
my_label = Label(root, image=aspen)
my_label.pack(pady=20)

#Entry Box
my_entry = Entry(root, font=("Helvetica", 24))
my_entry.pack(pady=20)

# Button
my_button = Button(root, text="Add Text To Image",
	command=add_it, font=("Helvetica", 24))
my_button.pack(pady=20)

root.mainloop()

John Elder

John is the CEO of Codemy.com where he teaches over 100,000 students how to code! He founded one of the Internet's earliest advertising networks and sold it to a publicly company at the height of the first dot com boom. After that he developed the award-winning Submission-Spider search engine submission software that's been used by over 3 million individuals, businesses, and governments in over 42 countries. He's written several Amazon #1 best selling books on coding, and runs a popular Youtube coding channel.

View all posts

Add comment

Your email address will not be published. Required fields are marked *

John Elder

John is the CEO of Codemy.com where he teaches over 100,000 students how to code! He founded one of the Internet's earliest advertising networks and sold it to a publicly company at the height of...