image - python如何支持在画布或标签小部件上显示图像?
问题描述
问题不在于 Python 是否支持图像的显示,而在于它如何支持图像的显示。我选择使用Python 2.7,并且安装了Tkinter和Image库/模块。我没有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
解决方案
对于后面的其他人来说,似乎可以通过使用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 色图像,而不是全彩色图像。
推荐阅读
- mysql - 与 MYSQL 数据库的连接在 excel 中不可见
- r - R Shapefile地图阴影基于映射在其上的经纬度点
- c# - 如何加速无尽的跑步者
- android - 尝试打开相机时颤动 image_picker 提供程序错误
- python - python 将在不同来源中创建的 json dict 合并到 1 dict json
- api - 如何在 Web 请求中知道 API 的数据?
- image-processing - CVAT 注释工具。包括自己的 DL 模型
- node.js - 如何使 quick.db 异步读取
- mysql - Mysql过滤并显示不包含特定单词的条目
- android - 如何更改项目语言项目“存储库”