Simple Python Painter
Over the last Couple days I have been working on a simple painter project using Python and the tkinter libraries.
Creating a Simple Paint Program using Python & Tkinter
Below is the source code.
Introduction
Paint programs are popular applications that allow users to unleash their creativity by drawing and manipulating images. In this tutorial, we will explore how to create a simple yet functional paint program using Python and Tkinter. Tkinter is a widely-used library for GUI development in Python and provides an easy way to create interactive applications. By following this step-by-step guide, you will gain a deep understanding of the code and be able to customize and enhance the paint program according to your needs.
Prerequisites:
To follow along with this tutorial, you will need a basic understanding of Python programming and familiarity with Tkinter library. Make sure you have Python installed on your system.
Setting up the Environment:
- Importing the Required Libraries:
Begin by importing the necessary libraries for the paint program. We need the following:
import tkinter
import os
from tkinter import *
from tkinter import colorchooser, filedialog
from PIL import Image, ImageTk
Here, we import tkinter
for GUI development, os
for file operations, colorchooser
and filedialog
for color selection and file dialog windows, and Image
and ImageTk
from PIL for image handling.
- Initializing Variables:
Next, initialize the variables that will be used throughout the program.
prev_x = None
prev_y = None
brush_color = "black"
The prev_x
and prev_y
variables will store the previous coordinates of the mouse cursor during drawing to ensure smooth lines. brush_color
is a global variable that holds the current selected color for the brush, and it is initially set to “black”.
Creating the Paint Program Interface:
- Creating the Main Window and Toolbar:
root = Tk()
root.title("Painter1")
toolbar = Frame(root, width=100, bg="gray")
toolbar.pack(side="left", fill="y")
We create the main window using Tk()
and set its title to “Painter1”. Then, we create a toolbar frame with a width of 100 pixels and a background color of gray. The toolbar frame is packed to the left side of the window and fills the available vertical space.
- Adding Buttons and Controls to the Toolbar:
Now, let’s add buttons and controls to the toolbar for various functionalities.
brush_button = Button(toolbar, text="Brush", command=switch_to_brush)
brush_button.pack()
erase_button = Button(toolbar, text="Eraser", command=switch_to_eraser)
erase_button.pack()
brush_size_label = Button(toolbar, text="Brush Size", bg="gray")
brush_size_label.pack()
brush_size_slider = Scale(toolbar, from_=1, to=10, orient="vertical", length=150, command=change_brush_size)
brush_size_slider.set(5)
brush_size_slider.pack()
brush_color_button = Button(toolbar, text="Color", command=lambda: change_brush_color(colorchooser.askcolor()[1]))
brush_color_button.pack()
paint_bucket_button = Button(toolbar, text="Fill", command=paint_bucket)
paint_bucket_button.pack()
import_image_button = Button(toolbar, text="Import", command=import_image)
import_image_button.pack()
export_image_button = Button(toolbar, text="Export", command=export_image)
export_image_button.pack()
clear_canvas_button = Button(toolbar, text="Clear Canvas", command=clear_canvas)
clear_canvas_button.pack()
Here, we create buttons for brush, eraser, brush size, brush color, fill, import image, export image, and clear canvas functionalities. These buttons are packed into the toolbar frame, and each button is associated with a specific command function that will be executed when the button is clicked.
- Creating the Canvas:
canvas = Canvas(root, width=800, height=600, bg="white")
canvas.pack()
We create a canvas using the Canvas()
function and set its width to 800 pixels, height to 600 pixels, and background color to white. The canvas is then packed into the main window.
Implementing Functionality:
- Handling Mouse Events for Drawing:
def paint(event):
global prev_x, prev_y
x, y = event.x, event.y
if prev_x is not None and prev_y is not None:
canvas.create_line(prev_x, prev_y, x, y, fill=brush_color, width=brush_size * 2)
prev_x, prev_y = int(x), int(y)
def start_paint(event):
global prev_x, prev_y
prev_x, prev_y = event.x, event.y
canvas.bind("<B1-Motion>", paint)
canvas.bind("<ButtonPress-1>", start_paint)
These functions handle the mouse events for drawing on the canvas. The paint()
function is called whenever the mouse is moved while the left mouse button is pressed. It retrieves the current cursor coordinates (x
and y
), draws a line on the canvas from the previous coordinates to the current coordinates using the selected brush color and size, and updates the previous coordinates. The start_paint()
function is called when the left mouse button is initially pressed, and it sets the initial coordinates for drawing.
- Changing Brush Size and Color:
def change_brush_size(new_size):
global brush_size
brush_size = int(new_size)
def change_brush_color(color):
global brush_color
brush_color = color
These functions are called when the brush size or color is changed. The change_brush_size()
function takes the new size as an argument, converts it to an integer, and updates the brush_size
variable. The change_brush_color()
function takes the selected color as an argument and updates the brush_color
variable.
- Paint Bucket Functionality:
def paint_bucket():
canvas.config(bg=brush_color)
This function is associated with the “Fill” button and changes the background color of the canvas to the selected brush color.
- Importing and Displaying Images:
def import_image():
file_path = filedialog.askopenfilename(filetypes=[("Image Files", "*.png;*.jpg;*.jpeg;*.gif")])
if file_path:
image = Image.open(file_path)
resized_image = image.resize((canvas.winfo_width(), canvas.winfo_height()))
canvas.image = ImageTk.PhotoImage(resized_image)
canvas.create_image(0, 0, anchor="nw", image=canvas.image)
This function is associated with the “Import” button and allows the user to select an image file from their system. It opens the image using PIL’s Image.open()
function, resizes it to fit the canvas dimensions, creates a PhotoImage object from the resized image, and displays the image on the canvas using create_image()
.
- Switching Between Brush and Eraser:
def switch_to_brush():
change_brush_color("black")
def switch_to_eraser():
change_brush_color("white")
These functions are associated with the “Brush” and “Eraser” buttons. They change the brush color to black or white, respectively, by calling the change_brush_color()
function.
- Clearing the Canvas:
def clear_canvas():
canvas.delete("all")
This function is associated with the “Clear Canvas” button and
removes all items drawn on the canvas by using the delete()
method with the argument “all”.
- Exporting the Canvas as an Image:
def export_image():
file_path = filedialog.asksaveasfilename(filetypes=[("PNG Image", "*.png"), ("JPEG Image", "*.jpg;*.jpeg"),
("GIF Image", "*.gif"), ("PDF Document", "*.pdf")])
if file_path:
if file_path.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
ps_file_path = file_path + ".ps" # Save the PostScript file path
canvas.postscript(file=ps_file_path, colormode="color")
img = Image.open(ps_file_path)
img.save(file_path)
img.close()
os.remove(ps_file_path) # Remove the temporary PostScript file
elif file_path.lower().endswith('.pdf'):
ps_file_path = file_path + ".ps" # Save the PostScript file path
canvas.postscript(file=ps_file_path, colormode="color")
img = Image.open(ps_file_path)
img.save(file_path, "PDF", resolution=100.0)
img.close()
os.remove(ps_file_path) # Remove the temporary PostScript file
This function is associated with the “Export” button and allows the user to save the canvas as an image file. It opens a file dialog window for the user to select the destination file path and format. Depending on the chosen format, the canvas is first converted to a PostScript file (ps_file_path
), which is then opened, saved in the desired format, and finally removed.
Conclusions:
Congratulations! You have successfully created a paint program using Python and Tkinter. Throughout this tutorial, we covered various aspects of building a functional paint program, including drawing on the canvas, changing brush size and color, using the paint bucket tool, importing and displaying images, switching between brush and eraser modes, clearing the canvas, and exporting the artwork as an image file. Feel free to explore further and enhance the program by adding additional features and functionality. Happy painting!
Filed under: Computer Information Systems - @ June 20, 2023 1:08 am