Python Forum

Full Version: GUI Speed
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I have programmed a game involving a tkinter canvas of 900x900,
divided into 60x60 cells of different colors.
To show each new situation, it takes some time (seconds),
and tests proved that updating the canvas takes more than half of that time.
So the question is, can i find a faster update mechanism than the one i implemented:
cell_size is obviously 15 pixels.(i also think cell size has no influence or very little)
def new_gen():
    for row in range(60):
        for col in range(60):
            y = row * cell_size
            x = col * cell_size
            Kanvas.create_rectangle(x,y,x+cell_size,y+cell_size,fill='somecolor')
    root.update()
Paul
Can you supply an example that will run?
I sure can:

import random
from tkinter import *
import time

# GUI
root = Tk()
root.geometry('900x900+250+100')
root.title('Test')
root.configure(background='grey')
Kanvas = Canvas(root,width=900, height=900, bg='grey')
Kanvas.pack()    

colors = ('white','yellow','green','red')
def new_sit():
    for row in range(60):
        for col in range(60):
            color= random.choice(colors)
            y = row * 15 
            x = col * 15
            Kanvas.create_rectangle(x,y,x+15,y+15,fill=color)
    root.update()
    
steps = 0
while True:
    steps += 1
    Kanvas.delete('all')
    print(f'Step {steps}')
    new_sit() 
   
root.mainloop()
When I ran this code the canvas update takes 0.14 seconds. I shaved a whole 3% off by using Canvas.itemconfig to set the rectangle color instead of deleting all the rectangles and making a new grid. Tkinter is doggy doing normal things and this is not the kind of thing it is meant to do. Those rectangles are all objects, not just a drawing on the canvas. This is not much different than drawing a panel with 3600 buttons then delete. Repeat.

Have you thought about doing whatever it is you are trying to do using PyGame? PyGame should be faster at drawing.
(Jul-20-2020, 06:25 PM)deanhystad Wrote: [ -> ]I shaved a whole 3% off by using Canvas.itemconfig to set the rectangle color instead of deleting all the rectangles

Thanks for your efforts. Any improvement is significant because i view this from the
perspective of many inerations (steps). I will look into the "item-config", which i did not know of.

Your remark about the cells being objects, put me on the trace of another possible improvement.
If i can determine the predominant color beforehand, i don't need to create those objects,
if the canvas is that color already.
If all that is not satisfactory, maybe pygame will come into the picture, which i never used before.

thx,
Paul