我有一个巨 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): example0

And after a few seconds: example1

因此,执行迭代的时间保持不变.但在两次迭代之间,持续时间会随着时间的推移而不断增加.我不明白特金特为什么放慢了脚步.

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

推荐答案

在添加形状时,您不仅仅是给像素上色.您可以创建带有上下文的图形,并将它们存储到内存中.而不是滥用Canvas绘制一幅画,并显示这幅画在Canvas,这将是快得多,并将为您提供更多的 Select ,以 colored颜色 您的图像,而不是你想要绘制.

Python相关问答推荐

如何使用stride_tricks.as_strided逆转NumPy数组

如何用symy更新分段函数

提取两行之间的标题的常规表达

在Python中对分层父/子列表进行排序

如何自动抓取以下CSV

点到面的Y距离

Python json.转储包含一些UTF-8字符的二元组,要么失败,要么转换它们.我希望编码字符按原样保留

Python上的Instagram API:缺少client_id参数"

PMMLPipeline._ fit()需要2到3个位置参数,但给出了4个位置参数

我如何使法国在 map 中完全透明的代码?

对所有子图应用相同的轴格式

将9个3x3矩阵按特定顺序排列成9x9矩阵

从一个系列创建一个Dataframe,特别是如何重命名其中的列(例如:使用NAs/NaN)

有没有一种ONE—LINER的方法给一个框架的每一行一个由整数和字符串组成的唯一id?

UNIQUE约束失败:customuser. username

如何在Python 3.9.6和MacOS Sonoma 14.3.1下安装Pyregion

获取PANDA GROUP BY转换中的组的名称

我可以不带视频系统的pygame,只用于游戏手柄输入吗?''

如何防止html代码出现在quarto gfm报告中的pandas表之上

如何在Python中解析特定的文本,这些文本包含了同一行中的所有内容,