I've been wanting to make a sorting algorithm visualizer using python and settled to use the Tkinter library as my way of visualizing the data (if anyone has better libraries to use I'm open to suggestions, I looked into matplotlib but became discouraged). My problem is that as I'm sorting the array, I want to make a swap, show the updated array after the swap, then continue the sorting; but what ends up happening is that the array sorts and then the entire sorted array is updated.
import tkinter as tk
from tkinter import ttk
import random
import time
class SortingVisualizer(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "Sorting Visualizer")
tk.Tk.wm_minsize(self, width=600, height=500)
tk.Tk.wm_resizable(self, width=False, height=False)
self.topFrame = tk.Frame(self)
self.topFrame.grid(row=0, sticky='w')
self.sortOptions = ['Select Algorithm','Bubble sort','Quicksort', 'Merge sort']
self.optionVar = tk.StringVar()
self.optionDrop = ttk.OptionMenu(self.topFrame, self.optionVar, *self.sortOptions)
self.optionDrop.config(width=15)
self.optionDrop.grid(row=0, column=1, sticky='ew')
self.sortButton = ttk.Button(self.topFrame, text = "Sort", command = lambda: bubbleSort(self))
self.sortButton.grid(row=0, column=2, sticky='w')
self.genButton = ttk.Button(self.topFrame, text = "Generate New Array", command = self.newArray)
self.genButton.grid(row=0, column=0)
self.generateArray()
def newArray(self):
self.sortCanvas.destroy()
self.generateArray()
def generateArray(self):
self.array = []
self.numOperations = 0
i = 0
while i < 15:
height = random.randint(15, 200)
self.array.append(height)
i = i + 1
self.drawCanvas()
def drawCanvas(self):
self.sortCanvas = tk.Canvas(self, width=600, height=450)
self.sortCanvas.grid(row=1)
self.sortCanvas.create_line(15, 15, 585, 15)
label = "Number of Operations: " + str(self.numOperations)
self.numLabel = tk.Label(self.topFrame, text = label)
self.numLabel.grid(row=1)
bar_width = 20
bar_gap = bar_width + 10
start_x = 30
start_y = 15
for bar_height in self.array:
x1 = start_x + bar_width
y1 = start_y + bar_height
self.sortCanvas.create_rectangle(start_x, start_y, x1, y1*2, fill='green')
start_x = start_x + bar_gap
def redrawCanvas(self):
self.sortCanvas.destroy()
self.drawCanvas()
def bubbleSort(self):
n = len(self.array)
for i in range(n):
for j in range(0, n-i-1):
if self.array[j]>self.array[j+1]:
temp = self.array[j]
self.array[j] = self.array[j+1]
self.array[j+1] = temp
self.numOperations += 1
self.after(300, self.redrawCanvas)
app = SortingVisualizer()
app.mainloop()
I have also tried app.after(300, self.redrawCanvas) and get the same result