I am trying to create a simple sorting visualizer in python using Tkinter. With that being said, I would like the user to be able to see the changes that occur in each iteration of the sorting algorithm (whatever algorithm is used) and in order to do so, I have to "pause" the program for the user to see the changes each tick.
It's the "pausing" part that confuses me. I looked into time.sleep which is irrelevant for GUI programs (due to the mainloop) and after() in the Tkinter library, but I can't seem to get it right.
My code:
arr = [random.randint(0,600) for i in range(100)]
WIN_WIDTH = 1200
WIN_HEIGHT = 800
BAR_NUM = len(arr)
BAR_WIDTH = WIN_WIDTH // BAR_NUM
class sortVisualizer(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
canvas = tk.Canvas(root,width=WIN_WIDTH,height=WIN_HEIGHT)
self.draw(canvas)
canvas.pack()
queue = [self.bubbleSort(canvas)] //theres going to be more than just one sorting algorithm
queue[0]
def re_draw(self,canvas,index1,index2):
canvas.delete("all")
temp = arr[index1]
arr[index1] = arr[index2]
arr[index2] = temp
for i in range(BAR_NUM):
canvas.create_rectangle(BAR_WIDTH * i,
WIN_HEIGHT - arr[i],
BAR_WIDTH * (i+1),
WIN_HEIGHT,
fill = "white")
canvas.pack()
def bubbleSort(self,canvas):
for item in range(len(arr)-1,0,-1):
for i in range(item):
if (arr[i] > arr[i+1]):
self.re_draw(canvas,i,i+1)
There are a few other functions in the sortVisualizer class but they are irrelevant.
So my question is: how will I be able to "pause" or "stop" the program in order for the user to be see the changes in each tick?