How do i draw in python - Create Paint Tool using Python
Published February 07, 2022In this python example, we will create a simple painting tool using Python. Using this drawing tool, we will be able to draw an image or write a text by moving the cursor. To create this tool, we are going to use the Python Tkinter Library, which is the pre-installed library for creating GUI applications.
How to create a paint tool using Python
Below are the steps to create a Python paint tool.
Step 1: Add the following code to your application to import the Tkinter library:
from tkinter import * |
Step 2: Create a canvas on the window and set its dimensions.
root.title("Python Paint Tool") root.geometry("500x350") wn=Canvas(root, width=500, height=350, bg='white') |
Running this code will display an empty Tkinter canvas window
![]() |
However, you cannot draw on this canvas windows. We'll create the main function that enables drawing in the next step.
Step 3: Create a function to get the mouse movement with the four coordinates, X1,y1, X2, y2 and display it in canvas
def paint(event): # get x1, y1, x2, y2 co-ordinates x1, y1 = (event.x-3), (event.y-3) x2, y2 = (event.x+3), (event.y+3) color = "black" # display the mouse movement inside canvas wn.create_oval(x1, y1, x2, y2, fill=color, outline=color) |
Step 4: We must now bind the main function to the cursor movement
wn.bind('<B1-Motion>', paint) wn.pack() |
Step 5: Now run the paint tool. Now. we can draw or write on the window with the paint tool
Complete example code for Draw in python using python paint tool
from tkinter import * root = Tk() root.title("Python Paint Tool") root.geometry("500x350") def paint(event): x1, y1 = (event.x-3), (event.y-3) x2, y2 = (event.x+3), (event.y+3) color = "black" wn.create_oval(x1, y1, x2, y2, fill=color, outline=color) wn=Canvas(root, width=500, height=350, bg='white') wn.bind('<B1-Motion>', paint) wn.pack() root.mainloop() |
Output
![]() |
Conclusion: In this python example we created simple pain tool using Tkinter and draw on the canvas
Article Contributed By :
|
|
|
|
341 Views |