欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python使用tkinter加载png、jpg等图片

时间:2021-08-15 09:33:37|栏目:Python代码|点击:

首先PhotoImage注意这里只支持gif格式的图片

photo = PhotoImage(file="D:/python/images/02.gif")

发现tkinter是只支持gif的格式,如果要加载png或者jpg的话就要使用PIL模块

from tkinter import *
from PIL import Image, ImageTk

root = Tk()
root.title('测试组python毕业题')

img = Image.open('ques.png')  # 打开图片
photo = ImageTk.PhotoImage(img)  # 用PIL模块的PhotoImage打开
imglabel = Label(root, image=photo)
imglabel.grid(row=0, column=0, columnspan=3)

Label(root, text="Answer:").grid(row=1, column=0, sticky=S + N)

answerEntry = Entry(root)
btn = Button(root, text="Submit", command='submit')

answerEntry.grid(row=1, column=1)
btn.grid(row=1, column=2)

mainloop()

但运行时会报

ModuleNotFoundError: No module named 'PIL'

运行命令:

pip install pillow

D:\Program Files\Python37>pip install pillow
Collecting pillow
  Downloading https://files.pythonhosted.org/packages/40/f2/a424d4d5dd6aa8c26636969decbb3da1c01286d344e71429b1d648bccb64/Pillow-6.0.0-cp37-cp37m-win_amd64.whl (2.0MB)
     |????????????????????????????????| 2.0MB 133kB/s
Installing collected packages: pillow
Successfully installed pillow-6.0.0

D:\Program Files\Python37>

如果运行该命令 显示

Requirement already satisfied: Pillow in c:\program files (x86)\python\lib\site-packages (3.4.2)

则表示已经安装过了

如果已安装则先卸载以获取最新的pillow
运行命令: pip uninstall pillow
然后运行:pip install pillow
就可以了

补充:解决python tkinter 展示jpg、png格式图片的问题

报错:

from tkinter import *
 
img = PhotoImage(file = r'D:\test\hero\暗黑元首\暗黑元首.jpg')
lable_show = Label(frame_show,imag = img)

解决:首先安装PIL库,使用pip命令

pip install pillow

然后使用PIL库获得ImageTk.PhotoImage对象代替tk.PhotoImage对象即可

from PIL import Image,ImageTk
 
img = ImageTk.PhotoImage(Image.open(r'D:\test\hero\暗黑元首\暗黑元首.jpg'))
lable_show = Label(frame_show,imag = img)

上一篇:selenium判断元素是否存在的两种方法小结

栏    目:Python代码

下一篇:Keras中的多分类损失函数用法categorical_crossentropy

本文标题:Python使用tkinter加载png、jpg等图片

本文地址:http://www.codeinn.net/misctech/166938.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有