Add Scrollbar to Canvas in Tkinter

The Canvas widget is popularly used in Tkinter for the drawing of shapes, images and text. Often, to save space, we do not show everything inside the Canvas at the same time. Instead we limit the “viewable” region in the Canvas and add a Tkinter Scrollbar to navigate it.


Creating a Scrollbar in a Canvas

Here is the full code for creating a (empty) Canvas in Tkinter, with a vertical scrollbar attached. (Full explanation is also included after the output)

from tkinter import *
 
root = Tk()
 
frame=Frame(root, width=300,height=300)
frame.pack(expand = True, fill=BOTH)
 
canvas = Canvas(frame,bg='white', width = 300,height = 300,
              scrollregion=(0,0,500,500))
 
vbar = Scrollbar(canvas, orient = VERTICAL)
vbar.pack(side = RIGHT, fill = Y)
vbar.config(command = canvas.yview)
 
canvas.config(width=300,height=300)
canvas.config(yscrollcommand=vbar.set)
canvas.pack(side=LEFT, expand = True, fill = BOTH)

root.mainloop()

The output:

Add Scrollbar to Canvas in Tkinter

Now let’s do a little step-by-step explanation.

canvas = Canvas(frame, bg='white', width=300, height=300,
              scrollregion=(0,0,500,500))

This line creates a Canvas widget and adds it to the Frame widget. The canvas is configured with a white background, a width of 300 pixels, and a height of 300 pixels. The scrollregion option is also set to a tuple defining the size of the scrollable area as (0, 0, 500, 500), which means that the scrollable area is 500 pixels wide and 500 pixels tall.

Next up, we create a vertical Scrollbar widget (whether it’s vertical or horizontal is decided by the orient parameter)

vbar = Scrollbar(canvas, orient = VERTICAL)
vbar.pack(side = RIGHT, fill = Y)
vbar.config(command = canvas.yview)

The pack method is used to position the scrollbar on the right side of the frame and fill it vertically. The command option is then set to the yview method of the Canvas widget, which links the scrollbar to the canvas.

Now we connect our Scrollbar and Canvas widget.

canvas.config(yscrollcommand=vbar.set)

Here we set the yscrollcommand option of the canvas to the set method of the Scrollbar widget, which links the canvas to the scrollbar.

canvas.pack(side=LEFT, expand = True, fill = BOTH)

The expand and fill options are set to True and BOTH respectively, which causes the canvas to expand to fill the entire frame and both the horizontal and vertical directions. (otherwise the canvas won’t resize when the window resizes itself)

You can also add a horizontal scrollbar too!


This marks the end of the Add Scrollbar to Canvas in Tkinter Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions about the tutorial content can be asked in the comments section below.

Leave a Comment