Вы можете использовать after()
для замены внешней петли for
в bubbleSort()
и вызова drawRandomLines()
внутри bubbleSort()
:
from tkinter import *
import random
height, width = 350, 600
thickness = 5
# create the random lines
randomLines = [random.randint(1, height-1) for i in range(0, width, thickness)]
master = Tk()
w = Canvas(master, width=width, height=height)
w.pack()
def drawRandomLines():
w.delete("all")
for i in range(len(randomLines)):
x = i * thickness
# use bars for more clearly presentation
w.create_rectangle(x, height, x+thickness, height-randomLines[i], fill='red')
def bubbleSort(passnum):
for i in range(passnum):
if randomLines[i] > randomLines[i+1]:
randomLines[i], randomLines[i+1] = randomLines[i+1], randomLines[i]
drawRandomLines()
if passnum > 0:
master.after(20, bubbleSort, passnum-1)
else:
w.create_text(50, 50, text='Done!', font=('Arial', 24))
drawRandomLines() # show initial order of lines
bubbleSort(len(randomLines)-1)
master.mainloop()