首页 > 解决方案 > python如何支持在画布或标签小部件上显示图像?

问题描述

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

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

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 窗口时,python 分别抛出 TclError 和 Runtime 错误。消息是:使用 PhotoImage 时“创建图像为时过早”,使用 Label 时“图像不存在”(我的代码中的第 8 行)。任何人都可以在不建议我将模块添加到我的 python(版本:2.7)安装的情况下提供帮助吗?

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

有用的stackoverflow问题,供参考:

•<a href="https://stackoverflow.com/questions/23901168/how-do-i-insert-a-jpeg-image-into-a-python-tkinter-window">如何插入 JPEG 图像进入 python Tkinter 窗口?

•<a href="https://stackoverflow.com/questions/10133856/how-to-add-an-image-in-tkinter">如何在Tkinter中添加图片?

•<a href="https://stackoverflow.com/questions/28762116/cannot-construct-tkinter-photoimage-from-pil-image">无法从 PIL Image 构造 tkinter.PhotoImage

标签: imagepython-2.7tkinterphotoimage

解决方案


对于后面的其他人来说,似乎可以通过使用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 色图像,而不是全彩色图像。


推荐阅读