python - Tkinter 图像渲染速度很慢。我应该如何改进呢?

标签 python python-3.x tkinter tkinter-canvas

我设置了一个引擎,并且我必须使用的所需 GUI 库(并且只有我可以使用的非内置库)是 tkinter。虽然我在 TK 方面经验不是很丰富,但我希望帮助提高我的渲染性能。我实现渲染的方式大致如下:

# assign png as PhotoImage
Resources.register(PhotoImage, '...circle-alpha.png')

# init window and canvas
root = Tk()
root.geometry = "600x1000"

canvas = Canvas(root, width=600, height=1000)
canvas.pack()

# using root.after I call this function every ~33ms
def main_loop():
  canvas.delete(ALL)
  Camera.main_camera.render()

# camera.render eventually calls this:
# sprite.image references the prviously-mentioned image
def render(self, camera):
  canvas.create_image(self.pos.x, self.pos.y, image=self.sprite.image

所以它的作用是: 对于每个附加了渲染器的对象,主摄像头会检查是否可以看到该对象。 如果是这样,该对象将在 Canvas 上创建其图像。 此过程完成后, Canvas 将被清除并重复该过程

问题: 此过程可能需要超过指定的 33 毫秒才能在屏幕上移动 1 128x128 png。有哪些方法可以改进我的渲染方法?

最佳答案

您不应该在每次想要移动 Canvas 图像时都重新创建它。相反,只需创建一次图像并将其保存到变量:my_image = canvas.create_image(self.pos.x, self.pos.y, image=self.sprite.image) .

当您调用create_image时方法,它返回 Canvas 与图像关联的整数值,因此您可以稍后在代码中使用它对图像执行操作,例如移动它: canvas.moveto(my_image, self.pos.x, self.pos.y) 。所以render()函数看起来像这样:

def render(self, camera):
    canvas.moveto(my_image, self.pos.x, self.pos.y)

关于python - Tkinter 图像渲染速度很慢。我应该如何改进呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69164390/

相关文章:

Python 高效排序字典中的并行列表

python - 如何在 TkInter 中创建平铺布局/流布局?

python-3.x - 在 tkinter.text 小部件中隐藏键入的字符

python - 具有重叠组/窗口的 Pandas groupby

python - PPM 图像到 Python 中的 ASCII 艺术

python - 嵌套字典的划分

Python 文本小部件仅在窗口中打开

python - 生成所有 n 选择 k 个二元向量 python

python - Pandas 数据框,如何按多列分组并对特定列应用总和并添加新的计数列?

python - 使用 matplotlib.pyplot 绘制多个字典值