estephan500
estephan500

Reputation: 200

why does tkinter / window.update get slower over time within my program?

I find that when I call window.update, it operates much faster when fewer things have been written to the window, but then later on, when I have written more elements to the window, window.update takes longer.

See my code below. You can see it adds new circles to the screen 100 at a time before updating the window.

My question is: Why does it get slower over time? At the very beginning, the refreshing happens many times per second. After a half a minute, it will be once per second or so...

At first this seemed odd to me, because I thought that simply changing the pixels to be refreshed, and then refreshing, would remain the same amount of processing each time. But then I thought... is this thing continuing to "keep track of" and "account for" the previous shapes that I had previously placed on the window??

Anyway, do you have thoughts or answers on why it slows down?

from tkinter import *
from random import *
xsize=1000
ysize=1000
shapesize=10
window = Tk()
canvas = Canvas(window, width=xsize, height=ysize)
canvas.pack()
while True:
    for l in range(100):
        col=choice(['pink','green','orange','yellow','blue','purple','red','black','brown','gray'])
        x=randint(0,xsize)
        y=randint(0,ysize)

        canvas.create_oval(x,y,x+shapesize, y+shapesize, fill=col) 
    window.update()

Upvotes: 2

Views: 2025

Answers (1)

Andath
Andath

Reputation: 22714

Short answer:

That is due to the complexity of the algorithm you use.

Detailed answer:

The while condition is indefinitely satisfied.

Right away after the for loop exits, you ask the canvas to redraw all the previous ovals.

This means:

  • while iteration 1, canvas redraws 99 ovals
  • while iteration 2: canvas redraws 99 + 99 ovals
  • while iteration 3: canvas redraws 99 + 99 + 99 ovals.
  • while iteration 4: canvas redraws 99 + 99 + 99 + 99 ovals.
  • ...
  • ... OMG !!!

Conclusion

You got what you asked for.

Alternative

If you want to keep drawing only 99 ovals indefinitely, then delete each previous 99 ovals you previously created. This means, you can add canvas.delete(ALL) right below canvas.update()

Upvotes: 5

Related Questions