简体   繁体   中英

How can I make this Tkinter app run faster

I've written a simple Conway's Game of Life in Python Tk, but it is so utterly slow!
On my PC it ran somewhat fine, but on my school computers it couldn't reach 10 refreshes a second. I suspect the drawing part lags a lot, how can I fix that?

def drawCells(self):
    self.board.delete(tk.ALL)
    for i in range(self.gridsize):
        for j in range(self.gridsize):
            if self.cnow[j][i] == 1: # cells now list
                rect = self.board.create_rectangle(
                    i * self.grid,
                    j * self.grid,
                    (i + 1) * self.grid,
                    (j + 1) * self.grid,
                    fill="#000000")

I don't know if pasting the entire class is necessary, but if needed I'll append the rest of the code.

Creating items on the canvas is slow, and the more you create the slower it gets (even if you delete them each time). Instead, create the rectangles once and then simply reconfigure them on each generation.

The create_rectangle method returns an integer id. Save these ids, then use the itemconfigure method to change the color.

All I can suggest is rewriting the code without embedding two for-loops (that'll improve your time complexity some), but I'm not sure if that'll fix your problem entirely as I do not know what else is going on in your class.

Best of luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM