Here we are providing basic tutorial in Tkinter on introduction to canvas.

Sample code

The following Tkinter code will demonstrate the same:

from tkinter import *

root = Tk()
canvas = Canvas(root, width=300, height=300)
canvas.pack()
canvas.create_rectangle(20,20,100,270)


root.mainloop()


In the above code, we created a canvas object named canvas using Canvas method. Parameters passed to the function are root window, width and height of the canvas required. After that the canvas is packed to display on the GUI window. Then, using the method create_rectangle of canvas class, we created a rectangle of desired size and coordinates.

Output

output


Another example to demonstrate the canvas

In this example, we created a rectangle, a line and a polygon as shown in the below code.

Sample code

The following Tkinter code will demonstrate the same:

from tkinter import *

root = Tk()
canvas = Canvas(root, width=300, height=300)
canvas.pack()
canvas.create_rectangle(20,20,100,270)
canvas.create_line(0,0,300,300)
canvas.create_polygon(10,10,20,50,30,60,40,20,50,10)

root.mainloop()


Output

output


Another example to demonstrate the canvas

In this example, we created a rectangle using a user defined method as shown in the below code. Also we used the functionality of fill to fill the color in the rectangle.

Sample code

The following Tkinter code will demonstrate the same:

from tkinter import *

root = Tk()
canvas = Canvas(root, width=300, height=300)
canvas.pack()

def createRect(x1,y1,x2,y2):
    canvas.create_rectangle(x1,y1,x2,y2,fill="blue")

createRect(5,5,200,100)

root.mainloop()


Output

output