Python TKinter:canvas 图像文件只包含一个黑色像素而不是 512x256 绿色像素,为什么?

Python TKinter: The canvas image file just contains one black pixel instead of 512x256 green pixels, why?

canvas_width = 512
canvas_height = 512
root = Tk()
canvas = Canvas(root, width=canvas_width, height=canvas_height)
canvas.pack()
canvas.create_rectangle(0, 0, canvas_width, canvas_height / 2, fill='green')
ps = canvas.postscript(colormode='color')
img = PIL.Image.open(io.BytesIO(ps.encode('utf-8')))
img.save("/home/test.png")

如果执行此代码,您会看到保存的文件 test.png 仅包含一个黑色像素。相反,它应该包含 512x256 绿色像素和 512x256 未定义颜色像素。

你知道为什么吗?

您必须在捕获前使用 canvas.update()canvas.update_idletasks() 重绘 canvas 事件。区别在于 update() 正在处理用户事件,而 update_idletasks() 只是强行重绘 window。只有这样,您才能捕获后记,因为所有文本和图形都已经存在,可以捕获并将其转换为图像。 希望对您有所帮助!