首先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'
運行命令:
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命令
然后使用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內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- python 實現在tkinter中動態顯示label圖片的方法
- python tkinter canvas 顯示圖片的示例
- python3 tkinter實現添加圖片和文本
- python Tkinter的圖片刷新實例
- Python tkinter實現圖片標注功能(完整代碼)
- python tkinter GUI繪制,以及點擊更新顯示圖片代碼
- Python3.4 tkinter,PIL圖片轉換
- 詳解python tkinter 圖片插入問題
- python利用tkinter實現圖片格式轉換的示例