LoginSignup
17
9

More than 5 years have passed since last update.

(備忘録)[Python + tkinter] tk.PhotoImage でエラーが出る

Posted at

備忘録。
下記ソースのtk.PhotoImageで画像を読み込む際、
image "pyimage2" doesn't exist
というエラーが出た。
読み込む画像の枚数によっては"pyimage3"とかになるみたい。

wrong.py
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import PhotoImage

root = tk.Tk()
root.title(u"TITLE")

img = "img.png"
img1 = tk.PhotoImage(file=img)        #ここ
label1 = ttk.Label(root,image=img1)
label1.grid(row=0,column=0)

root.mainloop()

調べた結果、tk.PhotoImageの引数としてmasterを指定する必要があって、その画像を表示するwidgetが格納される、rootなりframeなりを master=root のように明示すると解決した。

NG: img1 = tk.PhotoImage(file=img)
OK: img1 = tk.PhotoImage(file=img,master=root)

collect.py
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import PhotoImage

root = tk.Tk()
root.title(u"TITLE")

img = "img.png"
img1 = tk.PhotoImage(file=img,master=root) #ここ
label1 = ttk.Label(root,image=img1)
label1.grid(row=0,column=0)

root.mainloop()
17
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
9