Skip to content
Related Articles

Related Articles

Visualizing Bubble Sort using Tkinter in Python
  • Last Updated : 14 May, 2021

In this article, we will use the Python GUI Library Tkinter to visualize the Bubble Sort algorithm. 

  • Tkinter is a very easy to use and beginner-friendly GUI library that can be used to visualize the sorting algorithms.
  • Here Bubble Sort Algorithm is visualized which works by repeatedly swapping the adjacent elements/values if they are in the wrong order until the whole array is sorted.
  • The idea is that : if arr[i] > arr[i+1] then swap them.
  • In the first iteration, N-1 items have to be scanned and the largest element moves to its right position. In the second iteration, the second largest item will move to its correct position, and after the third iteration (stopping at item N-3) the third largest will be in place.  Therefore, to place all the elements in the correct order the above operation is performed N-1 times. This algorithm has Time Complexity = O(N2).


  1. A list of random values within a specified range is generated as bars.
  2. Different colors (red and green) are used to show the sorting process.
  3. A suitable “Speed” range bar is created for the ease of the user to visualize.
  4. “Generate” and “Start” buttons are created separately for the creation of data bars and initiation of the sorting process.

Extension Code for Bubble Sort :

This is the extension code for the bubble sort algorithm which is imported in the main Tkinter visualizer code to implement the bubble sort algorithm and return the sorted result. 


# Extension Bubble Sort Code
# importing time module
import time
# function to implement bubble sort by passing
# the following parameters:
# data is passed for the set of unsorted data values
# drawdata is used to generate the data bars
# timer iis for the speed range
def bubble(data, drawData, timer):
    n = len(data)
    for i in range(n):
        for j in range(0, n-i-1):
            if data[j] > data[j+1]:
                data[j], data[j+1] = data[j+1], data[j]
                # if swapped then color becomes Green else stays Red
                drawData(data, ['Green' if x == j +
                                1 else 'Red' for x in range(len(data))])
    # sorted elements generated with Green color
    drawData(data, ['Green' for x in range(len(data))])

Code for Tkinter :

In this code, we are generating the data values as bars of different lengths and a particular color. The basic layout is designed in a Tkinter ‘Frame’ and the portion when the bars are generated and the algorithm is visualized is designed in a Tkinter ‘Canvas’.

The code essentially has the following components:

  1. Mainframe: a Tkinter frame to arrange all the necessary components(labels, buttons, speed bar, etc.) in an organized manner
  2. Canvas: A Tkinter canvas used as the space where the generated data bars are drawn and the sorting process is visualized
  3. generate(): Method to generate the data values by accepting a range and then passing that as a parameter to the drawData() function
  4. drawData():  Method to generate bars to normalized data values(within the given range) of a particular color on the canvas
  5. start_algorithm(): This function is called when the “START” button is pressed. It initiates the sorting process by calling the bubble() function from the Bubble Sort Extension Code.


# code for Bubble Sort Visualizer using Python and Tkinter
from tkinter import *
from tkinter import ttk
import random
from bub_srt import bubble
# initialising root class for Tkinter
root = Tk()
root.title("Bubble Sort Visualizer")
# maximum window size
root.maxsize(900, 600)
select_alg = StringVar()
data = []
# function to generate the data values by accepting a given range
def generate():
    global data
    # minval : minimum value of the range
    minval = int(minEntry.get())
    # maxval : maximum value of the range
    maxval = int(maxEntry.get())
    # sizeval : number of data values/bars to be generated
    sizeval = int(sizeEntry.get())
    # creating a blank data list which will be further
    # filled with random data values
    # within the entered range
    data = []
    for _ in range(sizeval):
        data.append(random.randrange(minval, maxval+1))
    drawData(data, ['Red' for x in range(len(data))])
# function to create the data bars by creating a canvas in Tkinter
def drawData(data, colorlist):
    can_height = 380
    can_width = 550
    x_width = can_width/(len(data) + 1)
    offset = 30
    spacing = 10
    # normalizing data for rescaling real-valued numeric data within the
    # given range
    normalized_data = [i / max(data) for i in data]
    for i, height in enumerate(normalized_data):
        # top left corner
        x0 = i*x_width + offset + spacing
        y0 = can_height - height*340
        # bottom right corner
        x1 = ((i+1)*x_width) + offset
        y1 = can_height
        # data bars are generated as Red colored vertical rectangles
        canvas.create_rectangle(x0, y0, x1, y1, fill=colorlist[i])
        canvas.create_text(x0+2, y0, anchor=SE, text=str(data[i]))
# function to initiate the sorting process by
# calling the extension code
def start_algorithm():
    global data
    bubble(data, drawData, speedbar.get())
# creating main user interface frame and
# basic layout by creating a frame
Mainframe = Frame(root, width=600, height=200, bg="Grey")
Mainframe.grid(row=0, column=0, padx=10, pady=5)
canvas = Canvas(root, width=600, height=380, bg="Grey")
canvas.grid(row=1, column=0, padx=10, pady=5)
# creating user interface area in grid manner
# first row components
Label(Mainframe, text="ALGORITHM", bg='Grey').grid(
    row=0, column=0, padx=5, pady=5, sticky=W)
# algorithm menu for showing the name of the sorting algorithm
algmenu = ttk.Combobox(
    Mainframe, textvariable=select_alg, values=["Bubble Sort"])
algmenu.grid(row=0, column=1, padx=5, pady=5)
# creating Start Button to start the sorting visualization process
Button(Mainframe, text="START", bg="Blue", command=start_algorithm).grid(
    row=1, column=3, padx=5, pady=5)
# creating Speed Bar using scale in Tkinter
speedbar = Scale(Mainframe, from_=0.10, to=2.0, length=100, digits=2,
                 resolution=0.2, orient=HORIZONTAL, label="Select Speed")
speedbar.grid(row=0, column=2, padx=5, pady=5)
# second row components
# sizeEntry : scale to select the size/number of data bars
sizeEntry = Scale(Mainframe, from_=3, to=60, resolution=1,
                  orient=HORIZONTAL, label="Size")
sizeEntry.grid(row=1, column=0, padx=5, pady=5)
# minEntry : scale to select the minimum value of data bars
minEntry = Scale(Mainframe, from_=0, to=10, resolution=1,
                 orient=HORIZONTAL, label="Minimun Value")
minEntry.grid(row=1, column=1, padx=5, pady=5)
# maxEntry : scale to select the maximum value of data bars
maxEntry = Scale(Mainframe, from_=10, to=100, resolution=1,
                 orient=HORIZONTAL, label="Maximun Value")
maxEntry.grid(row=1, column=2, padx=5, pady=5)
# creating generate button
Button(Mainframe, text="Generate", bg="Red", command=generate).grid(
    row=0, column=3, padx=5, pady=5)
# to stop automatic window termination

Output :

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :