简体   繁体   English

如何使Tkinter应用运行得更快

[英]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! 我用Python Tk编写了一个简单的Conway的《生命游戏》,但它是如此之慢!
On my PC it ran somewhat fine, but on my school computers it couldn't reach 10 refreshes a second. 在我的PC上,它运行得还不错,但是在我的学校计算机上,每秒刷新不到10次。 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. create_rectangle方法返回一个整数ID。 Save these ids, then use the itemconfigure method to change the color. 保存这些ID,然后使用itemconfigure方法更改颜色。

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. 我只建议重写代码而不嵌入两个for循环(这会提高您的时间复杂度),但是我不确定这是否能完全解决您的问题,因为我不知道接下来会发生什么你的班。

Best of luck! 祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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