以下 python 程序创建一个 TkinterCanvas
对象并在其上绘制随机矩阵。它还测量进行 10 次后续更新所需的时间。正如您从下面的输出中可以看到的那样,这个时间在程序过程中持续且显着地增长。这种行为的原因是什么,我该如何解决?
from Tkinter import Tk, Canvas
import time
import numpy as np
window = Tk()
nRows = 30
nCols = 30
CELL_SIZE = 10
canvas = Canvas(window, width=CELL_SIZE*nRows,
height=CELL_SIZE*nCols)
canvas.pack()
def drawbox(m):
for y in range(nRows):
for x in range(nCols):
if m[y][x]:
color = '#00FF00'
else:
color = '#000000'
canvas.create_rectangle(CELL_SIZE*x,
CELL_SIZE*y,
CELL_SIZE*x+CELL_SIZE,
CELL_SIZE*y+CELL_SIZE,
fill=color,
outline="#000000", width=1)
count = 0
timeStart = time.time()
while(True):
board = np.random.rand(nRows, nCols) > 0.5
if count % 10 == 0:
print '%.1f seconds'%(time.time() - timeStart)
timeStart = time.time()
count = 0
count += 1
drawbox(board)
canvas.after(5)
canvas.update()
这是输出
0.0 seconds
1.7 seconds
4.1 seconds
6.3 seconds
8.7 seconds