Tkinter with Canvas – Rectangle

Canvas

Let’s take a look at Canvas. With this widget you can draw something on the window. The first thing that we are going to look at is how to create the canvas itself and then how to draw a rectangle in it.

Create the Canvas widget

As usual, we create the window.

# window

import tkinter as tk

root = tk.Tk()

root.mainloop()

And then we add the canvas widget:

# window

import tkinter as tk

root = tk.Tk()

canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()

root.mainloop()

Now we can draw a rectangle on the canvas, with a code like this:

# drawing a rectangle

# the arguments are coordinates of top left and bottom right vertex
# you give the rectangle a color with the fill parameter
canvas.create_rectangle(10, 10, 100, 100, fill='blue')

In the next paragraph, we will see an application of this code to draw rectangles where we click the mouse button.

Example: drawing rectangles

With this code, when you click on the window, a rectangle will be created.

import tkinter as tk

master = tk.Tk()


def rectangle(event):
    w.create_rectangle(event.x, event.y, event.x + 10, event.y + 10, fill="blue")


w = tk.Canvas(master, width=200, height=200)
w.pack()

master.bind("<Button-1>", rectangle)

master.mainloop()

 

Tkinter test for students

Tkinter articles

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.