Reputation: 645
I use python 3.7.9
on Windows. tkinter
version is 8.6.
I am following Here, and trying to use .png
image as a GUI background.
When I run #1, it throws an error. When I run #2, it works fine.
Official document says :
- PhotoImage for images in PGM, PPM, GIF and PNG formats. The latter is supported starting with Tk 8.6.
I found similar questions asked years ago, but that was when tkinter
had not yet supported .png
and they advised to use PIL
.
I checked my tkinter
version and it says 8.6, anyone could enlighten me what the problem is here?
Is the use of PIL
still officially required to handle png
?
On a side note, exact same error raised for #1 when I replaced .png
with .gif
as well.
---------------------------------------------------------------------------
TclError Traceback (most recent call last)
<ipython-input-2-4a440c40f4bf> in <module>
4 root = Tk()
5
----> 6 bg = PhotoImage(file='test.png')
7 bg_label = Label(root, image=bg)
8 bg_label.place(x=0, y=0, relwidth=1, relheight=1)
~\anaconda3\envs\my_env\lib\tkinter\__init__.py in __init__(self, name, cnf, master, **kw)
3543 Valid resource names: data, format, file, gamma, height, palette,
3544 width."""
-> 3545 Image.__init__(self, 'photo', name, cnf, master, **kw)
3546 def blank(self):
3547 """Display a transparent image."""
~\anaconda3\envs\my_env\lib\tkinter\__init__.py in __init__(self, imgtype, name, cnf, master, **kw)
3499 v = self._register(v)
3500 options = options + ('-'+k, v)
-> 3501 self.tk.call(('image', 'create', imgtype, name,) + options)
3502 self.name = name
3503 def __str__(self): return self.name
TclError: couldn't recognize data in image file "test.png"
from tkinter import *
root = Tk()
bg = PhotoImage(file='test.png')
bg_label = Label(root, image=bg)
bg_label.place(x=0, y=0, relwidth=1, relheight=1)
root.mainloop()
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
bg = ImageTk.PhotoImage(file='test.gif')
bg_label = Label(root, image=bg)
bg_label.place(x=0, y=0, relwidth=1, relheight=1)
root.mainloop()
Upvotes: 0
Views: 738
Reputation: 645
tkinter
version 8.6 does support .png
iamges.
The reason it wasn't working was the image I thought was a .png
file was actually not a .png
file. I downloaded the image originally as a .jpg
file and I simply changed the extension. Changing extensions does not change the file type itself.
I grabbed other .png
image and it worked fine.
Upvotes: 1