Tkinter Canvas
Draw on a Canvas
A Canvas is an area where you can draw lines, shapes and text:
Example
Draw a line:
import tkinter as tk
window = tk.Tk()
window.geometry("300x200")
canvas = tk.Canvas(window, bg="white",
width=280, height=180)
canvas.pack(pady=10)
canvas.create_line(20, 20, 260, 160)
window.mainloop()
Result:
bg sets the background color of the canvas.
create_line() draws a line from the point (20, 20) to the point (260, 160).
Note: On a canvas, (0, 0) is the top left corner, and y grows downwards. This is different from turtle, where (0, 0) is in the middle and y grows upwards.
Shapes
create_rectangle() and create_oval() draw a shape inside a box.
The four numbers are the top left corner and the bottom right corner of the box:
Example
Draw a square and a circle:
import tkinter as tk
window = tk.Tk()
window.geometry("300x200")
canvas = tk.Canvas(window, bg="white",
width=280, height=180)
canvas.pack(pady=10)
canvas.create_rectangle(20, 30, 120, 130,
fill="#04AA6D")
canvas.create_oval(160, 30, 260, 130,
fill="yellow")
window.mainloop()
Result:
fill sets the color inside the shape. An oval inside a square box is a circle.
Text
create_text() writes text on the canvas. The point is the middle of the text:
Example
Write text on the canvas:
import tkinter as tk
window = tk.Tk()
window.geometry("300x200")
canvas = tk.Canvas(window, bg="white",
width=280, height=180)
canvas.pack(pady=10)
canvas.create_text(140, 90, text="Hello!",
font=("Arial", 24))
window.mainloop()
Result:
Draw With the Mouse
With bind() from the Tkinter Events chapter, the user can draw on the canvas:
Example
Draw a dot where the user clicks:
import tkinter as tk
window = tk.Tk()
window.geometry("300x200")
def draw_dot(event):
x, y = event.x, event.y
canvas.create_oval(x-5, y-5, x+5, y+5,
fill="red")
canvas = tk.Canvas(window, bg="white",
width=280, height=180)
canvas.pack(pady=10)
canvas.bind("<Button-1>", draw_dot)
window.mainloop()
Result:
After clicking in a few places:
Each click draws a small circle, 10 pixels wide, around the point that was clicked.
Move a Shape
Each create_ method returns a number that identifies the shape. Use it with move() to move the shape:
Example
Move the ball with the right arrow key:
import tkinter as tk
window = tk.Tk()
window.geometry("300x200")
def move_right(event):
canvas.move(ball, 10, 0)
canvas = tk.Canvas(window, bg="white",
width=280, height=180)
canvas.pack(pady=10)
ball = canvas.create_oval(20, 70, 60, 110,
fill="red")
window.bind("<Right>", move_right)
window.mainloop()
Result:
After pressing the right arrow key 8 times:
move(ball, 10, 0) moves the ball 10 pixels to the right, and 0 pixels down.