首先PhotoImage注意這里只支持gif格式的圖片
photo = PhotoImage(file="D:/python/images/02.gif")
發(fā)現(xiàn)tkinter是只支持gif的格式,如果要加載png或者jpg的話就要使用PIL模塊
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
root.title('測試組python畢業(yè)題')
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()
但運(yùn)行時(shí)會(huì)報(bào)
ModuleNotFoundError: No module named 'PIL'
運(yùn)行命令:
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>
如果運(yùn)行該命令 顯示
Requirement already satisfied: Pillow in c:\program files (x86)\python\lib\site-packages (3.4.2)
則表示已經(jīng)安裝過了
如果已安裝則先卸載以獲取最新的pillow
運(yùn)行命令: pip uninstall pillow
然后運(yùn)行:pip install pillow
就可以了
補(bǔ)充:解決python tkinter 展示jpg、png格式圖片的問題
報(bào)錯(cuò):
from tkinter import *
img = PhotoImage(file = r'D:\test\hero\暗黑元首\暗黑元首.jpg')
lable_show = Label(frame_show,imag = img)
解決:首先安裝PIL庫,使用pip命令
然后使用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)
到此這篇關(guān)于Python使用tkinter加載png、jpg等圖片的文章就介紹到這了,更多相關(guān)tkinter加載png、jpg內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- python 實(shí)現(xiàn)在tkinter中動(dòng)態(tài)顯示label圖片的方法
- python tkinter canvas 顯示圖片的示例
- python3 tkinter實(shí)現(xiàn)添加圖片和文本
- python Tkinter的圖片刷新實(shí)例
- Python tkinter實(shí)現(xiàn)圖片標(biāo)注功能(完整代碼)
- python tkinter GUI繪制,以及點(diǎn)擊更新顯示圖片代碼
- Python3.4 tkinter,PIL圖片轉(zhuǎn)換
- 詳解python tkinter 圖片插入問題
- python利用tkinter實(shí)現(xiàn)圖片格式轉(zhuǎn)換的示例