Python Tkinter Canvas Tutorial

In this Python tutorial, we will discuss in detail Python Tkinter Canvas. We will cover the below topics also:

  • Python Tkinter Canvas Tutorial
  • Create Rectangle using Python Tkinter Canvas
  • Adding an image using Python Tkinter Canvas
  • Adding Text using Python Tkinter Canvas
  • Clearing Canvas objects in Python Tkinter Canvas
  • Working with Matploitlib in Python Tkinter Canvas
  • Change the size of Python Tkinter Canvas

Python Tkinter Canvas Tutorial

  • Like other widgets, the canvas is also a widget that is used for multiple uses.
  • Canvas is a drawing widget and it can hold other widgets as well.
  • Using canvas 2D objects can be created like text, circle, rectangle, etc.
  • In canvas, x & y coordinates have 0 value at the top left corner.
  • Moving to the right increases x value and Moving to the left increases y value.
  • The layer of python Tkinter canvas is decided on the basis of the sequence of placement, which means the object placed in end stys on the top layer.

If you are new to Python Tkinter or Python GUI programming, check out Python GUI Programming (Python Tkinter) and Python Tkinter drag and drop.

Python Tkinter Canvas Rectangle

  • Python Tkinter Canvas has built-in features to create shapes.
  • To create a rectangle create_rectangle() method is used.
  • This method accepts 4 parameters x1, y1, x2, y2. Here x1 and y1 are the coordinates for the top left corner and x2 and y2 are the coordinates for the bottom right corner.

Code:

Here is the code with explanation to create python tkinter rectangle using canvas.

from tkinter import *


ws = Tk()
ws.title('PythonGuides')
ws.geometry('300x300')
ws.config(bg='#345')

canvas = Canvas(
    ws,
    height=200,
    width=200,
    bg="#fff"
    )
    
canvas.pack()

canvas.create_rectangle(
    30, 30, 180, 120,
    outline="#fb0",
    fill="#fb0")

ws.mainloop()

Output:

In this output, rectangle is created using python tkinter Canvas.

python tkinter rectangle using canvas
python tkinter rectangle using canvas

If you are confused with x1, y1,x2, y2 coordinates then here is the explanation for the same. x1 pushes the object to the right side or in the East., y1 pushes the object towards the South direction. X2 and Y2 expand the rectangle in East & South directions.

python tkinter rectangle using canvas explanation
python tkinter rectangle using canvas

Python Tkinter Canvas Image

  • In this tutorial, we will learn to implement an image in Python Tkinter Canvas.
  • We have created a simple .png image using ms paint for demonstration purposes.
  • First, we will create a Canvas widget and provide height and width to it.
  • PhotoImage() the method is used to read the image and the value is stored in the img variable.
  • canvas.create_image(x, y, image=img_path)
  • Here, x expands the image towards the right whereas y expands the image downwards.
  • image option holds the file name.
READ:  NumPy Read CSV with Header in Python [3 Methods]

Code:

from tkinter import *
from tkinter import *

ws = Tk()
ws.title('PythonGuides')
ws.geometry('750x400')
ws.config(bg='#345')

canvas = Canvas(
    ws,
    height=500,
    width=1000,
    bg="#fff"
    )

canvas.pack()

img = PhotoImage(file="python-tkinter-canvas-image-for-use.png")
canvas.create_image(370, 200, image=img)

ws.mainloop()

Output:

In this output, image is displayed using canvas in Python Tkinter.

Python Tkinter Canvas Image
Python Tkinter Canvas Image

Python Tkinter Canvas Text

  • The text refers to the arrangement of the alphabet(s).
  • We can place text in python Tkinter canvas using canvas.create_text(x, y). Here x & y is the position of the text.

Code:

In this code, python tkinter canvas text is displayed.

from tkinter import *


ws = Tk()
ws.title('PythonGuides')
ws.geometry('500x300')
ws.config(bg='#345')

canvas = Canvas(
    ws,
    height=200,
    width=400,
    bg="#fff"
    )

canvas.pack()

canvas.create_text(
    200,100,
    fill="darkblue",
    font="Times 20 italic bold",
    text="with great power comes \ngreat responsibility")

ws.mainloop()

Output:

In this output, we can see that text is displayed using python tkinter canvas.

python tkinter canvas text
python tkinter canvas text

Python Tkinter Canvas Clear

  • In this section, we will learn to delete or clear the python Tkinter Canvas.
  • The delete method is used to clear the canvas or specific object of the canvas.
  • To delete the entire canvas, use canvas.delete("all")
    • Here canvas is the variable that stores the value of the Canvas widget.
    • all is a built-in feature that is used to delete everything inside the canvas.
    • To delete a specific object of the canvas, provide the tag name in place of “all”.
  • tags can be created by using the keyword tag followed by any name.
  • Example: canvas.create_rectangle(100, 30, 400, 200, fill=”red”, tags=”rect”)
    • canvas.delete("rect")
    • this code will delete only the rectangle having a tag as rect.
  • The same tag name can be provided to multiple objects.
  • And these objects will be deleted when the delete method is used for the provided tag.

code:

In this code, we have created multiple objects & we have created buttons to delete these objects. rectangles will be deleted when clicked on del_rect button, squares will be deleted when clicked on del_squ button and all the objects will be deleted when click on the del_all button.

from tkinter import *

ws = Tk()
ws.title('PythonGuides')
ws.geometry('500x400')
ws.config(bg='grey')

canvas = Canvas(
    ws,
    height=300,
    width=400,
    bg="#fff",
    )

canvas.pack()

canvas.create_rectangle(
    30, 20, 200, 100,
    fill="red", 
    tags="rect",
    )

canvas.create_oval(
    150, 150, 50, 50,
    fill="blue",
    tag="circ"
    )

canvas.create_rectangle(
    150, 50, 250, 150,
    fill="grey",
    tag="squa"
    )

canvas.create_text(
    180, 250,
    font= "Times 20",
    text="Squre,Circle & Rectangle \n inside the canvas",
    tag='txt'
    )

btn1 = Button(
    ws,
    text='del_rect',
    font="Times 12",
    command=lambda:canvas.delete("rect")
    )
 
btn1.pack(side=LEFT, fill=X, expand=True)

btn2 = Button(
    ws,
    text='del_squ',
    font="Times 12",
    command=lambda:canvas.delete("squa")
    )
 
btn2.pack(side=LEFT, fill=X, expand=True)

btn3 = Button(
    ws,
    text='del_circ',
    font="Times 12",
    command=lambda:canvas.delete("circ")
    )
 
btn3.pack(side=LEFT, fill=X, expand=True)

btn4 = Button(
    ws,
    text='del_all',
    font="Times 12",
    command=lambda:canvas.delete("all")
    )
 
btn4.pack(side=LEFT, fill=X, expand=True)


ws.mainloop()

Output:

READ:  How to convert a NumPy tuple to a list in Python [3 Methods]

In this output, circle, square, rectangle, and text is displayed. There are four buttons at the bottom. Each button will clear one object on the screen. del_all the button will clear everything on the canvas.

python tkinter canvas clear
Python Tkinter Canvas Clear

Python Tkinter Canvas Matplotlib

  • In this section, we will learn to use matplotlib in python Tkinter canvas
  • Matplotlib is a python library used for plotting data in a visual form. It is widely used in data analysis. It turns the data into graphs, histograms, etc.
  • matplotlib is an external library that needs to be installed before use.
  • pip install matplotlib this command will install matplotlib
  • once matplotlib is installed, we need to import the libraries.
  • backend_tkagg module is used to plot on canvas using matplotlib
  • This module is inside the matplotlib.backend.
  • Also, we need to import Figure from matplotlib. figure
  • Figure decides the size of the plotting area also provides an important toolbar.
Python Tkinter Canvas Matplotlib
Toolbar

Code:

In this code, We have plotted data using histogram.

from tkinter import *
from matplotlib.figure import Figure 
from matplotlib.backends.backend_tkagg import *

def click_toplot(): 
    fig = Figure(
        figsize = (5, 3),
        dpi = 100
        ) 

    #change this data to see difference
    y = [2, 10, 30, 10, 5, 8, 50, 44, 41] 

    plot1 = fig.add_subplot(111) 

    plot1.hist(y) 

    canvas = FigureCanvasTkAgg(
        fig,
        master = ws) 
    canvas.draw() 
    canvas.get_tk_widget().pack() 

    toolbar = NavigationToolbar2Tk(
        canvas,
        ws
        ) 

    toolbar.update() 
    canvas.get_tk_widget().pack() 


ws = Tk() 
ws.title('PythonGuides') 
ws.geometry("650x400") 
ws.config(bg='#fb0')

plot_button = Button(master=ws,
					command = click_toplot, 
					text = "Click to Plot") 

plot_button.pack() 

ws.mainloop() 

Output:

In this output, data is displayed in a histogram way.

python tkinter canvas matplotlib
Python Tkinter Canvas Matplotlib

Python Tkinter Canvas Size

  • Python Tkinter Canvas size can be decided by providing height and width.
  • Height is the vertical position of canvas on the parent window.
  • Width is the horizontal position of the canvas on the parent window.
  • Change in the height & width will change the size of the canvas.
canvas = Canvas(
    ws,
    height=200,
    width=400,
    bg="#fff"
    )

canvas.pack()
  • In this code, we are using the Canvas widget.
  • ws is the parent layer of Tkinter.
  • height provides vertical space to the canvas
  • width provides horizontal space to the canvas.
  • bg is used to provide background color to the canvas.
READ:  Python Scipy Confidence Interval [9 Useful Examples]

You may like the following Python Tkinter Canvas tutorials:

In this tutorial we have learned about python tkinter canvas, Also we have covered these topics.

  • Python Tkinter Canvas Tutorial
  • Create Rectangle using Python Tkinter Canvas
  • Adding an image using Python Tkinter Canvas
  • Adding Text using Python Tkinter Canvas
  • Clearing Canvas objects in Python Tkinter Canvas
  • Working with Matploitlib in Python Tkinter Canvas
  • Change the size of Python Tkinter Canvas