You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Tkinter使用create_image()时出现异常FPS下降问题求助

Tkinter Canvas 图像绘制性能异常问题

简介

代码仓库:Adril1n/tkinter_bug

演示代码如下:

import tkinter as tk
from PIL import Image, ImageTk
from time import time
import numpy as np

root = tk.Tk()
root.geometry('100x100')

canvas = tk.Canvas(root, width=100, height=100, bg="black")
canvas.place(x=0, y=0, anchor='nw')

root.bind('u', lambda e: switch_use_img())
def switch_use_img():
    global use_image
    use_image = not use_image

use_image = False

clr = "#"+("%06x"%int(np.random.default_rng(42).random()*16777215))
img = Image.new('RGBA', (28, 42), (*bytes.fromhex(clr[1:]), 255))
image = ImageTk.PhotoImage(img)


def update():
    canvas.delete('all')
    t = time()
    if use_image:
        for _ in range(5000):
            canvas.create_image(50, 50, anchor='c', image=image)
    else:
        for _ in range(5000):
            canvas.create_rectangle(50-14, 50-21, 50+14, 50+21, fill=clr, width=0)
    
    print(f"{'image' if use_image else 'rectangle'}:", (time()-t))
    
    dt = 1000//20 - int((time() - t)*10**3) # 20 : FPS
    print(dt)
    root.after(max(dt, 1), update)

update()
root.mainloop()

环境配置

  • Python版本:3.12.1
  • Conda版本:24.1.2
  • Tkinter版本:8.6.12
  • macOS版本:Sonoma 14.3.1 (23D60)
  • 设备:2020款M1 Air,16GB内存

该问题在Python 3.10.13、Tk 8.6.10环境下同样存在,但在macOS Monterey+Python 3.10.x环境下运行正常,无FPS下降。

问题描述

使用create_image()时单循环更新耗时更快,但整体FPS却显著下降。此代码是项目的演示版本。同时请教:是否应将该问题提交至cpython GitHub仓库?

更新测试

进一步测试后怀疑问题与多张图像的层叠有关,即多次调用create_image()绘制重叠图像时导致性能下降,但不确定——另一未绘制重叠图像的演示版本也出现了相同问题。

内容的提问来源于stack exchange,提问作者Adril1n

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 14:42:54