python 如何支持在 canvas 或标签小部件上显示图像?

How does python support the display of images on canvas or label widgets?

问题不在于Python是否支持图片显示,而是如何支持图片显示。我选择使用 Python 2.7,这有 TkinterImage libraries/modules 已安装。我没有 pygame 模块,它似乎很容易支持在图形用户界面上使用图像。

要打开系统上的文件或文件名,我正在使用 tkFileDialog 并且此模块按预期工作。然后,我可以将 tkFileDialog 命令的输出与 Image 模块结合起来创建一个图像对象(使用 open 方法)。完成此操作后,我可以使用 Image 的显示方法显示我的图形,如下所示:

import Image
import Tkinter
import tkFileDialog as File
root = Tkinter.Tk()
root.title('Image Test')
root.file = File.askopenfile()
root.image = Image.open(root.file)
root.label = Tkinter.Label(image=root.image)
root.label.grid()

Python 使用 Image Magick 呈现缩放图像,如果在第 7 行之后,我使用

root.image.show()

但是,当我尝试使用 Label(如我的代码所示)和 PhotoImage[ 将图像加载到 Tkinter window 时=46=] 小部件(被描述为支持图像显示)python 分别抛出 TclError 和运行时错误。消息是:使用 PhotoImage 时为 "too early to create image",使用 Label 时为 "image doesn't exist"(我的代码中的第 8 行)。任何人都可以在不建议我将模块添加到我的 python(版本:2.7)安装的情况下提供帮助吗?

我希望使用位图和 jpeg/jpg/jpe 图像。最好,我想使用 create_image 方法将图像加载到 Canvas 对象上。也就是说,当且仅当我可以将图像加载到 PhotoImage 对象(不包含代码)时。我将选择带有图像的 Label,最终将加载到 Canvas.

有用的Whosebug问题,供参考:

How do I insert a JPEG image into a python Tkinter window?

How to add an image in Tkinter?

对于下面的其他人来说,似乎可以通过使用 Image 模块打开他们的图像并以编程方式将其保存到 gif 文件类型。然后,使用 PhotoImage 模块将结果加载到 Canvas 小部件。

import Tkinter, Image, tkFileDialog as File
filename = File.askopenfilename() #choose jpg
image = Image.open(filename) 
image.save(fp='somename', format='GIF')
temporarygif = File.askopenfilename() #choose gift
photo = Tkinter.PhotoImage(file=temporarygif)
root = Tkinter.Tk()
root.title('Simple Image Display')
root.canvas = Tkinter. Canvas(root, options)
root.canvas.create_image(0,0,image=photo)
root.canvas.pack()
root.mainloop()

脑洞大开。

问题:保存的 gif 图像出现一些颜色质量损失。它看起来像 256 色 图像,而不是 全色 图像。