我有一个巨 Python 项目与tkinter.在这个项目上,我随着时间的推移画出了小方块. 我注意到随着正方形数量的增加,tkinter的速度变慢了.
下面是一个简单的例子,它在每次迭代中绘制200个红色方块:
import tkinter as tk
import random
import time
WIDTH = 900
CELL_SIZE = 2
GRID_WIDTH = int(WIDTH / CELL_SIZE)
CELL_PER_ITERATION = 200
SLEEP_MS = 50
root = tk.Tk()
canvas = tk.Canvas(root, width=WIDTH, height=WIDTH, bg="black")
canvas.pack()
current_iteration = 0
cell_count = 0
previous_iteration_end = time.time()
text = tk.Label(root, text=f"iteration {current_iteration}")
text.pack()
def draw_cell(x_grid, y_grid):
x = x_grid * CELL_SIZE
y = y_grid * CELL_SIZE
canvas.create_rectangle(x, y, x + CELL_SIZE, y + CELL_SIZE, fill="red")
def iteration():
global current_iteration
global previous_iteration_end
global cell_count
current_iteration_start = time.time()
for _ in range(CELL_PER_ITERATION):
draw_cell(
x_grid=random.randint(0, GRID_WIDTH),
y_grid=random.randint(0, GRID_WIDTH),
)
cell_count += 1
current_iteration_end = time.time()
# duration of this iteration
current_iteration_duration = current_iteration_end - current_iteration_start
# duration between start of this iteration and end of previous iteration
between_iteration_duration = current_iteration_start - previous_iteration_end
current_iteration += 1
text.config(text=f"iteration {current_iteration} | cell_count: {cell_count} | iter duration: {int(current_iteration_duration*1000)} ms | between iter duration: {int(between_iteration_duration*1000)} ms")
previous_iteration_end = current_iteration_end
def main_loop():
iteration()
root.after(ms=SLEEP_MS, func=main_loop)
root.after(func=main_loop, ms=SLEEP_MS)
root.mainloop()
Which gives (time data is written at the bottom of picture):
因此,执行迭代的时间保持不变.但在两次迭代之间,持续时间会随着时间的推移而不断增加.我不明白特金特为什么放慢了脚步.
Is it redrawing the entire canvas (so all already drawn squares) at each iteration ? Is there a way to avoid this slow down ?个
Note: This is an example, the real project i am working on looks like this: 100