5

I am using Tkinter to write a GUI and want to display a png file in a Tkiner.Label. So I have some code like this:

self.vcode.img = PhotoImage(data=open('test.png').read(), format='png')
self.vcode.config(image=self.vcode.img)

This code runs correctly on my Linux machine. But when I run it on my windows machine, it fails. I also tested on several other machines (include windows and linux), it failed all the time.

The Traceback is:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
    return self.func(*args)
  File "C:\Documents and Settings\St\client\GUI.py", line 150, in showrbox
    SignupBox(self, self.server)
  File "C:\Documents and Settings\St\client\GUI.py", line 197, in __init__
    self.refresh_vcode()
  File "C:\Documents and Settings\St\client\GUI.py", line 203, in refresh_vcode
    self.vcode.img = PhotoImage(data=open('test.png').read(), format='png')
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 3323, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 3279, in __init__
   self.tk.call(('image', 'create', imgtype, name,) + options)
TclError: image format "png" is not supported

If I delete format='png' in the source code, the traceback will become:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
    return self.func(*args)
  File "C:\Documents and Settings\St\client\GUI.py", line 150, in showrbox
    SignupBox(self, self.server)
  File "C:\Documents and Settings\St\client\GUI.py", line 197, in __init__
    self.refresh_vcode()
  File "C:\Documents and Settings\St\client\GUI.py", line 203, in refresh_vcode
    self.vcode.img = PhotoImage(data=open('test.png').read())
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 3323, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 3279, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
TclError: couldn't recognize image data

So, what should I do to make it support png files?

martineau
  • 119,623
  • 25
  • 170
  • 301
zsrkmyn
  • 547
  • 1
  • 5
  • 20
  • 1
    Have you tried using a different file format? See e.g. [here](http://effbot.org/tkinterbook/photoimage.htm). – jonrsharpe Dec 22 '14 at 08:53
  • 1
    @jonrsharpe, yes, I have tried 'gif' format, it shows the image on my linux machine, but shows a black (or white or some noise) area on my windows machine. – zsrkmyn Dec 22 '14 at 09:00
  • 1
    What did you use to convert the image? Does it display correctly on all machines *outside* the `Tk` app? – jonrsharpe Dec 22 '14 at 09:01
  • 1
    @jonrsharpe, I use nothing to convert the image, it's just a image downloaded from internet. Of course I tested several other images, all failed. The image can be displayed correctly outside the `Tk` app(using 'windows image and fax viewer' on windows or 'feh' on linux). – zsrkmyn Dec 22 '14 at 09:21
  • 1
    So you're just telling tkinter it's a gif while it's still actually a png? Why did you think that would work?! *Convert it.* – jonrsharpe Dec 22 '14 at 10:18
  • @jonrsharpe, sorry I didn't express myself clearly. I mean I tried 'gif' format using **another** gif images, not the 'png' one and it shows the image correctly on my linux machine, but shows a black (or white or noisy sometimes) area on my windows machine. – zsrkmyn Dec 22 '14 at 13:58

8 Answers8

19

PIL is now replaced by Pillow http://pillow.readthedocs.io/en/3.2.x/

solution:

from Tkinter import *
import PIL.Image
import PIL.ImageTk

root = Toplevel()

im = PIL.Image.open("photo.png")
photo = PIL.ImageTk.PhotoImage(im)

label = Label(root, image=photo)
label.image = photo  # keep a reference!
label.pack()

root.mainloop()

If PIL could not be found in code, you do need a pillow install:

pip install pillow
themefield
  • 3,847
  • 30
  • 32
HCLivess
  • 1,015
  • 1
  • 13
  • 21
  • 4
    this question doesn't involve the use of PIL, so it's not clear how you think this relates to the question. – Bryan Oakley Jan 27 '17 at 17:20
  • 1
    I don't understand. Do you want to rewrite PIL completely for it to be usable instead? I just provided a simplest solution. – HCLivess Sep 09 '17 at 13:49
  • 4
    The question doesn't ask anything about PIL or Pillow, but your statement is "PIL is replaced by Pillow". If I were the OP I would be saying "ok, why does that matter?" I think if you rephrase the opening paragraph to say something like "Tkinter doesn't support png, you'll need to use Pillow to create an image Tkinter recognizes", the answer will be better. Just saying "PIL is replaced by Pillow" when the question doesn't mention PIL or Pillow is confusing. You must remember that you are writing answers for someone who knows next to nothing about tkinter, PIL or Pillow. – Bryan Oakley Sep 09 '17 at 14:21
  • 2
    You are right, I was taking into consideration the selected answer. – HCLivess Sep 09 '17 at 15:35
  • 2
    Pillow 5.1 and python 3.5, imports had to change to `from PIL import Image, ImageTk` – Giannis Jun 10 '18 at 15:15
11

tkinter only supports 3 file formats off the bat which are GIF, PGM, and PPM. You will either need to convert the files to .GIF then load them (Far easier, but as jonrsharpe said, nothing will work without converting the file first) or you can port your program to Python 2.7 and use the Python Imaging Library (PIL) and its tkinter extensions to use a PNG image.

A link that you might find useful: http://effbot.org/tkinterbook/photoimage.htm

Benjamin James Drury
  • 2,353
  • 1
  • 14
  • 27
  • 1
    Thanks. And I'm sorry that I didn't express myself clearly. I mean I tried 'gif' format using another gif images, not the 'png' one and it shows the image correctly on my linux machine, but shows a black (or white or noisy sometimes) area on my windows machine as I said to jonrsharpe. Finally, I found it failed if I use `self.vcode.img = PhotoImage(data=open('test.gif').read(), format='gif')`. but it can work correctly if I use `self.vcode.img = PhotoImage(file='test.gif')` – zsrkmyn Dec 22 '14 at 14:55
  • 6
    tk 8.6 supports .png. The Widows 3.4.z installers install tcl/tk 8.6.z On *nix, it depends on what the system comes with and what a user upgrades to. That is why your program could work with one machine and ont another. OSX will have 8.5.z unless a user somehow upgrades. The PSF 3.5 installers for OSX will install 8.6 if it is then possible. – Terry Jan Reedy Dec 22 '14 at 22:40
  • @TerryJanReedy That's news to me but certainly news I'm glad to hear. I'll bare this in mind for future reference. – Benjamin James Drury Dec 22 '14 at 22:42
  • @TerryJanReedy Thank god I read your comment, that probably saved me *a lot* of time. – Hubro Oct 21 '15 at 11:40
  • 1
    Correction: the PSF *3.6* (not 3.5) installers will, hopefully, install tk 8.6. For 3.5, one can use a different installer, such as one from 'Homebrew'. I am not on OSX and don't know the pros and cons of alternate Python-Mac installers. – Terry Jan Reedy Oct 22 '15 at 02:26
  • The mentioned link does not exits anymore. – Faraaz Kurawle Sep 30 '21 at 07:38
4

Tkinter 8.6 supports png file format while tkinter 8.5 does not. If you have the option upgrade python and you should be fine to use png. If you have to use an older version of python you should use Pillow (maintained pil fork) which also works on python3.

If you are starting a new project do not use python2 or PIL as suggested in the accepted answer, they are both depreciated technologies.

timeyyy
  • 654
  • 9
  • 20
2

Fixed in official python.org 64-bit (only) installer for OS X. Tk version 8.6 is included out of the box. Warning: if you use homebrew, as of this post doing brew install python3 will only give you 8.5, and 8.6 is required to use png so you'll have to use official installer instead. To check which Tk you are using:

$ python3 -c 'import tkinter; print(tkinter.TkVersion);'

If it report 8.6, you are good to go.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
cmaceachern
  • 419
  • 4
  • 10
0

try with PIL library instead of converting your image to GIF, PGM, or PPM (PhotoImage) only accept these 3 formats.

import tkinter as tk
import PIL.Image
import PIL.ImageTk

base = tk.Tk()
base.title("Dialy Dose")

logoPath = r"C:\Users\saigopi\Downloads\logo.png"

ref = PIL.Image.open(logoPath)
photo = PIL.ImageTk.PhotoImage(im)

inputEdit = tk.Label(base,text="Enter Quote")
save = tk.Button(base,text="Save",background="green",command=save())
logo = tk.Label(base,image=photo,text="Logo bro lite")
quote = tk.Label(base,text="I am saying you are more than something")

inputEdit.pack()
save.pack()
logo.pack()
quote.pack()

base.mainloop()
saigopi.me
  • 14,011
  • 2
  • 83
  • 54
0
from tkinter import *
from tkinter import messagebox
import os
from PIL import Image, ImageTk


root = Tk()
root.geometry("1300x720")
root.title("KEDİLERİMİZ ve KÖPEKLERİMİZ")
class Ana:
    def __init__(self,name,roll):
        self.name = name
        self.roll = roll
resim = Label(root,width=77,height=43,bg="blue")
resim.place(x=730,y=10)
o = "1.PNG"
hu = o.find(".")
mu = o[hu:]
if mu == ".gif" or mu == ".png":
    img = PhotoImage(file = o)
else:
    photo = Image.open(o)
    img = ImageTk.PhotoImage(photo)
resim.configure(image=img,width=img.width(),height=img.height())
resim.image = img
0

on windows you gotta use this specific format:

Example = PhotoImage(file='photo.png')

and if you wish to resize it to a smaller size:

Example = Example.subsample(2, 2)

or

Example = Example.subsample(3, 3)

Total Code:

Example = PhotoImage(file='photo.png')
Example = Example.subsample(1, 1)

but future warning, you gotta file the file location in with the photo unless you put the photo in the same file as the script!

Gonzalez
  • 68
  • 5
0

I used PhotoImage to add my Gui an icon with png format. Like in below, It can work or give you an idea.

iconn = PhotoImage(file = "arcen.png" )
root.iconphoto(0, iconn)
dralioz
  • 49
  • 5