ImageTk 和 PIL 不能正确显示 png 图像
ImageTk and PIL do not display png image correctly
我目前正在尝试使用 PIL 和 Tkinter 模块在 python 中编写某种映射工具。到目前为止,几乎一切正常 quite。在 ui 的设置过程中,创建了一个虚拟图像(基于几个输入的 png 文件),这似乎也运行良好。但是,当尝试使用 ImageTk.Photo 在 canvas 中显示此图片时,显示的内容肯定不是图片。出于调试原因,我通过在 PIL.Image 本身上使用 show 方法输出了我的图片。
但是 show 方法显示的内容和 canvas 显示的内容有些不同 - 我无法找出解决方案,希望得到帮助。
首先是代码摘录(我只展示了canvas的初始化和图片的显示,因为整个代码会很长,我猜里面不会再提供了)。
这是canvas初始化的代码摘录(我显示的是一张全黑的图片,直到用户加载了显示图片所需的所有资源):
self.tileset_canvas = tkinter.Canvas(root, width=1024, height=1024)
self.tileset_canvas.create_line(0, 0, 80, 80)
self.tileset_raw_image = ImageTk.PhotoImage(PImage.new("RGB", (1024, 1024), "black"))
self.tileset_canvas_image = self.tileset_canvas.create_image(0, 0, image=self.tileset_raw_image)
self.tileset_canvas.grid(row=4, column=6, sticky=tkinter.W)
此外,在另一种方法中,我更改了图像的显示:
merged_img = PImage.new("RGB", (128, 512))
merged_img.paste(tsp_img, (0, 0))
merged_img.paste(tss_img, (0, 320))
merged_img = merged_img.resize((1024, 1024)) #Double the view for a better mapping expierience
merged_img = merged_img.convert(mode="RGB")
self.tileset_raw_image = ImageTk.PhotoImage(merged_img)
merged_img.show()
self.tileset_canvas.itemconfig(self.tileset_canvas_image, image=self.tileset_raw_image)
如你所见,我也调用了 show 方法来查看图片的实际效果。
这是显示方法在图片上调用时的输出:
然而,这是 ui 中显示的内容:
对于任何关心的人来说,图像似乎不仅正确锚定,而且固定在 canvas 的中间。
我目前正在尝试使用 PIL 和 Tkinter 模块在 python 中编写某种映射工具。到目前为止,几乎一切正常 quite。在 ui 的设置过程中,创建了一个虚拟图像(基于几个输入的 png 文件),这似乎也运行良好。但是,当尝试使用 ImageTk.Photo 在 canvas 中显示此图片时,显示的内容肯定不是图片。出于调试原因,我通过在 PIL.Image 本身上使用 show 方法输出了我的图片。
但是 show 方法显示的内容和 canvas 显示的内容有些不同 - 我无法找出解决方案,希望得到帮助。
首先是代码摘录(我只展示了canvas的初始化和图片的显示,因为整个代码会很长,我猜里面不会再提供了)。
这是canvas初始化的代码摘录(我显示的是一张全黑的图片,直到用户加载了显示图片所需的所有资源):
self.tileset_canvas = tkinter.Canvas(root, width=1024, height=1024)
self.tileset_canvas.create_line(0, 0, 80, 80)
self.tileset_raw_image = ImageTk.PhotoImage(PImage.new("RGB", (1024, 1024), "black"))
self.tileset_canvas_image = self.tileset_canvas.create_image(0, 0, image=self.tileset_raw_image)
self.tileset_canvas.grid(row=4, column=6, sticky=tkinter.W)
此外,在另一种方法中,我更改了图像的显示:
merged_img = PImage.new("RGB", (128, 512))
merged_img.paste(tsp_img, (0, 0))
merged_img.paste(tss_img, (0, 320))
merged_img = merged_img.resize((1024, 1024)) #Double the view for a better mapping expierience
merged_img = merged_img.convert(mode="RGB")
self.tileset_raw_image = ImageTk.PhotoImage(merged_img)
merged_img.show()
self.tileset_canvas.itemconfig(self.tileset_canvas_image, image=self.tileset_raw_image)
如你所见,我也调用了 show 方法来查看图片的实际效果。
这是显示方法在图片上调用时的输出:
然而,这是 ui 中显示的内容:
对于任何关心的人来说,图像似乎不仅正确锚定,而且固定在 canvas 的中间。