Python Tkinter Canvas

In this tutorial, we will learn about Python Tkinter Canvas. Python Tkinter Canvas allows us to add graphics in our Python application. With the help of Tkinter Canvas, we can draw lines, circles, add images and other widgets. Furthermore, we can draw graphs and plots with the help of Tkinter Canvas. Let’s start with a small example Here we will try to draw a line in =Tkinter Canvas. We will provide a total of four coordinates mean a total of four integer values like this(x1,y1) and (x2,y2).

Syntax to add Python Tkinter Canvas:

w = Canvas (master, options)
  • master: This represents the parent window.
  • options: Here is the list of most commonly used options for this widget.

Example to Draw a line in Tkinter Canvas

from tkinter import *
mainWindow = Tk()

#Setting height and width of canvas
canvasWindow = Canvas(mainWindow, 
           width=200,
           height=200)

canvasWindow.pack()

#Getting mid of canvas vertically
screenMid = int(200 / 2)

# creating line in cavas using create_line method
canvasWindow.create_line(0, screenMid, 200, screenMid, fill="#333")

mainloop() 

Here you can see how we can create a simple line using create_line method in Tkinter Canvas. Here we draw a horizontal line. I will recommend you to draw a vertical line by yourself. It will help you to understand this create_line method. Let’s move to the next example. In the next example, we will learn how we can create a rectangle in our Tkinter Canvas.

Example to Draw a rectangle in Python Tkinter Canvas

from tkinter import *
mainWindow = Tk()

#Setting height and width of canvas
canvasWindow = Canvas(mainWindow, 
           width=300,
           height=200)

canvasWindow.pack()

# creating line in cavas using create_line method
canvasWindow.create_rectangle(50, 50, 250, 150, fill="red")

mainloop() 

Various Possible Options in Python Tkinter Canvas

Option Description
bd This option we can use to set border width of the canvas in pixels. By default width is 2px.
bg This option we can use to set the background colour of the canvas.
confine This option we can use to make canvas un scrollable.
height This option we can use to set the height of the canvas.
relief This option we can use to set border type. The possible types are SUNKEN, RAISED, GROOVE, and RIDGE.
width This option we can use to set width of canvas.
Spread the love
Scroll to Top