Home > Net >  Is there a way to resize tkinter objects and see the resize in action?
Is there a way to resize tkinter objects and see the resize in action?

Time:10-01

I am trying to make a sorting algorithm animation, but i cant seem to find a way to make the program show the rectangles with random height resize into rectangles with sorted height. if you run the script, it'll show just the sorted rectangles without any animation.

import math
import time
import turtle
import random
import array
from tkinter import *


root = Tk()
canvas = Canvas(width=1100, height=900)
a = array.array('i',(0 for c in range(0,22)))
list = []
for i in range(0,22,1):
   a[i] = random.randrange(100,700,10)
   list.append( canvas.create_rectangle(i*50, 900, (i*50) 50, a[i], fill='white',outline="black") )
for v in range(0,22):
    for b in range(v,22):
        if a[b] < a[v]:
            sus = a[v]
            a[v] = a[b]
            a[b] = sus
for o in range(0,22):
   x0, y0, x1, y1 = canvas.coords(list[o])
   y0 = a[o]
   canvas.coords(list[o], x0, y0, x1, y1)
canvas["bg"] = "black"
canvas.pack()
root.mainloop()

CodePudding user response:

You need to pack the canvas before running the loops, and then call canvas.update() and time.sleep() while running the loops, so that the window shows, and sorts slow enough that you can see the animation. Here is the code, with moved and added lines marked accordingly:

import math
import time
import turtle
import random
import array
from tkinter import *


root = Tk()
canvas = Canvas(width=1100, height=900)
canvas.pack() ### MOVED LINE
canvas["bg"] = "black" ### MOVED LINE

a = array.array('i',(0 for c in range(0,22)))
list = []

for i in range(0,22,1):
    a[i] = random.randrange(100,700,10)
    list.append( canvas.create_rectangle(i*50, 900, (i*50) 50, a[i], fill='white',outline="black") )

for v in range(0,22):
    for b in range(v,22):
        if a[b] < a[v]:
            sus = a[v]
            a[v] = a[b]
            a[b] = sus

for o in range(0,22):
    x0, y0, x1, y1 = canvas.coords(list[o])
    y0 = a[o]
    canvas.coords(list[o], x0, y0, x1, y1)
    canvas.update() ### ADDED LINE
    time.sleep(0.1) ### ADDED LINE
root.mainloop()

Here, it calls time.sleep(0.1), so that the window waits ⅒ of a second between "frames" of the animation. You can use any time you want in place of this.

  • Related