TKinter Drawing

TKinter is the easiest way to get drawing in Python.

If you are going to draw in Tkinter you’ll need a canvas.  The following code sets you up with a basic window and canvas in Python 3.4

#import the Tkinter library from tkinter 
import *

#create a basic window.
window = Tk()

#give the window a title
window.title("Basic Window")

#Create a black canvas
canvas = Canvas(bg="white", width=400, height=300) canvas.pack()

Once you have a canvas you can start to think about how you might draw on it. Of course you might want to include images, animated Gifs or just draw straight onto the canvas. Once you have drawn objects onto the Canvas you can manipuate and interact with them using the Canvas Methods. The following images show my planning, complete code and the resulting window.  

There are a number of shapes that you can draw directly onto the canvas such as:

Rectangles and Squares

#Shape A 
canvas.create_rectangle(20,20,50,60,width=2,fill="red")

#Shape B
canvas.create_rectangle(80,30,140,50,width=2,fill="blue")

Ovals and Circles

#Shape C 
canvas.create_oval(170,20,270,160,width=2,fill="yellow")

Lines

#Shape D 
canvas.create_line(310, 110, 360, 60, width=5, fill="blue")

Polygons

Drawing a polygon is slightly different to a line or eclipse in that it has more than just two sets of x/y coordinates.

#Shape E 
points = [70, 110, 90, 150, 130, 170, 90, 190, 70, 230, 50, 190, 10, 170, 50, 150]
canvas.create_polygon(points, width=2, fill='green', outline='blue')

Arcs

Drawing an arc gives you three options: ARC, PIESLICE or CHORD. An arc is shown below with a cord being joined across its points and a pieslice which connects via the centre.

#Shape F 
canvas.create_arc(190, 210, 240, 270, width=2, fill="blue", style=CHORD) #Shape G
canvas.create_arc(280, 260, 330, 200, width=2, fill="blue", style=PIESLICE)

Bitmaps

Bitmaps can be used to draw two colour images.  

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.