脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python使用tkinter加载png、jpg等图片

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

2021-10-07 10:46市井白丁 Python

这篇文章主要介绍了Python使用tkinter加载png、jpg等图片,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

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

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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'

运行命令:

?
1
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格式图片的问题

报错:

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

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

?
1
pip install pillow

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

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

到此这篇关于Python使用tkinter加载png、jpg等图片的文章就介绍到这了,更多相关tkinter加载png、jpg内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/u010921682/article/details/89848375

延伸 · 阅读

精彩推荐