Visualizing Bubble Sort using Tkinter in Python

10 Sep, 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).
Procedure:
A list of random values within a specified range is generated as bars.Different colors (red and green) are used to show the sorting process.A suitable “Speed” range bar is created for the ease of the user to visualize.“Generate” and “Start” buttons are created separately for the creation of data bars and initiation of the sorting process.
A list of random values within a specified range is generated as bars.
Different colors (red and green) are used to show the sorting process.
A suitable “Speed” range bar is created for the ease of the user to visualize.
“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. 
Python3
# Extension Bubble Sort Code# importing time moduleimport 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 rangedef 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))])                time.sleep(timer)             # 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:
Mainframe: a Tkinter frame to arrange all the necessary components(labels, buttons, speed bar, etc.) in an organized mannerCanvas: A Tkinter canvas used as the space where the generated data bars are drawn and the sorting process is visualizedgenerate(): Method to generate the data values by accepting a range and then passing that as a parameter to the drawData() functiondrawData():  Method to generate bars to normalized data values(within the given range) of a particular color on the canvasstart_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.
Mainframe: a Tkinter frame to arrange all the necessary components(labels, buttons, speed bar, etc.) in an organized manner
Canvas: A Tkinter canvas used as the space where the generated data bars are drawn and the sorting process is visualized
generate(): Method to generate the data values by accepting a range and then passing that as a parameter to the drawData() function
drawData():  Method to generate bars to normalized data values(within the given range) of a particular color on the canvas
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.
Python3
# code for Bubble Sort Visualizer using Python and Tkinterfrom tkinter import *from tkinter import ttkimport randomfrom bub_srt import bubble # initialising root class for Tkinterroot = Tk()root.title("Bubble Sort Visualizer") # maximum window sizeroot.maxsize(900, 600)root.config(bg="Black")select_alg = StringVar()data = [] # function to generate the data values by accepting a given rangedef 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 Tkinterdef drawData(data, colorlist):    canvas.delete("all")    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]))    root.update_idletasks() # function to initiate the sorting process by# calling the extension codedef start_algorithm():    global data    bubble(data, drawData, speedbar.get())  # creating main user interface frame and# basic layout by creating a frameMainframe = 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 componentsLabel(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 algorithmalgmenu = ttk.Combobox(    Mainframe, textvariable=select_alg, values=["Bubble Sort"])algmenu.grid(row=0, column=1, padx=5, pady=5)algmenu.current(0) # creating Start Button to start the sorting visualization processButton(Mainframe, text="START", bg="Blue", command=start_algorithm).grid(    row=1, column=3, padx=5, pady=5) # creating Speed Bar using scale in Tkinterspeedbar = 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 barssizeEntry = 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 barsminEntry = Scale(Mainframe, from_=0, to=10, resolution=1,                 orient=HORIZONTAL, label="Minimum Value")minEntry.grid(row=1, column=1, padx=5, pady=5) # maxEntry : scale to select the maximum value of data barsmaxEntry = Scale(Mainframe, from_=10, to=100, resolution=1,                 orient=HORIZONTAL, label="Maximum Value")maxEntry.grid(row=1, column=2, padx=5, pady=5) # creating generate buttonButton(Mainframe, text="Generate", bg="Red", command=generate).grid(    row=0, column=3, padx=5, pady=5) # to stop automatic window terminationroot.mainloop()
Output :
simmytarika5
surindertarika1234
Python Tkinter-projects
Python-tkinter
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list