はじめに
Pythonでtkinterを用いてJPEG画像の表示を試みた際、下記2つのエラーに遭遇した。
自分と同じようなエラーに遭遇した初学者向けに、内容と対処方法についてメモしておく。
①TclError:couldn't open .png: no such file or directory
内容
同じフォルダ内に画像が格納されていない時に起こるエラー。ファイルや画像を格納したフォルダを指定してプログラムを実行しないと、同様なエラーが生じる。
対処
①ファイルと画像が同じフォルダに格納されているか確認する。
②格納したフォルダを指定してプログラムを実行しているか確認する。
TclError:couldn't recognize data in image file
内容
「tkinter」では標準でJPEGファイルを表示できないため、画像データを読み取ってもらえず生じたエラー。下記のような記述でJPEG画像の表示を試みるとエラーが生じる。
NG_CASE_JPEG.py
import tkinter
root = tkinter.Tk()
cvs = tkinter.Canvas(width=400, height=400)
img = tkinter.PhotoImage(file="~.jpg") #PNGなら問題なく表示可能/JPEGは不可
cvs.create_image(200, 200, image=img)
cvs.pack()
root.mainloop()
対処
Pillowを導入して画像を読み込み、tkinterで表示できるように設定する。
具体的には下記のような記述になる。
OK_CASE_JPEG.py
import tkinter
from PIL import Image, ImageTk # Pillowのインポート
img = Image.open("~.jpg")# 画像の読み込み
root = tkinter.Tk()
cvs = tkinter.Canvas(width=400, height=400)
tk_image = ImageTk.PhotoImage(image=img)# Pillowで読み込んだ画像をtkinterで表示できるよう設定
cvs.create_image(200, 200, image=tk_image)
cvs.pack()
root.mainloop()
※あらかじめPillowをpipやcondaを用いてインストールする必要あり。
最後に
記載内容に誤りなどありましたら、ご指摘いただけますと幸いです。