首先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)
到此这篇关于Python使用tkinter加载png、jpg等图片的文章就介绍到这了,更多相关tkinter加载png、jpg内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!