Getting PNGs to Python [duplicate] - python

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?

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

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

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.

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.

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

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!

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()

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)

Related

tkinker error: couldn´t recognize data in image file

I´m new to python and have problems with tkinker and the Images.
My error is:
Traceback (most recent call last):
File "D:/python/First Project/Weather app.py", line 12, in <module>
background_image = tk.PhotoImage(file='landscape.jpg')
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 3542, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 3498, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "landscape.jpg"
and the associated code is:
import tkinter as tk
root = tk.Tk()
background_image = tk.PhotoImage(file='D:\python\First Project\landscape.jpg')
background_label = tk.Label(root, image=background_image)
background_label.place(relwidth=1, relheight=1)
root.mainloop()
The ending of the file isn´t renamed and originally .jpg.
I also tried to edit it with
background_image = ImageTk.PhotoImage(Image.open('your.png'))
The PhotoImage method does not appear to support JPG files. I received the same error (couldn't recognise data in "image.jpg") when using a JPG file. When using a PNG file I did not receive any such errors.
Note that you cannot just change the file extension of a JPG file to turn it into a PNG file, because the data in PNG files is different from a JPG file. You will need to convert your JPG file to a PNG (or any other image file type supported by the PhotoImage method.)

Tkinter Label image setting won´t work

I've been learning how to use Tkinter from scratch and while I try to set a simple Label widget in a frame:
from Tkinter import *
from ttk import *
root = Tk()
root.title("Practice")
mainW = LabelFrame(root, text = "Main info")
mainW.grid()
image = Label(mainW, image = "C:\Users\Oscar Ramirez\Pictures\image.png")
image.grid(column = 0, row = 0)
codeEntry = Entry(mainW, text = "User Code")
codeEntry.grid(column = 1, row = 0)
root.mainloop()
I'm getting the following error:
Traceback (most recent call last):
File "Tutorial.py", line 10, in <module>
image = Label(mainW, image = "C:\Users\Oscar Ramirez\Pictures\image.png")
File "C:\Python27\lib\lib-tk\ttk.py", line 757, in __init__
Widget.__init__(self, master, "ttk::label", kw)
File "C:\Python27\lib\lib-tk\ttk.py", line 555, in __init__
Tkinter.Widget.__init__(self, master, widgetname, kw=kw)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2096, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image specification must contain an odd number of elements
I've checked the image format, the route, etc. And now I don't really know what can be causing me trouble.
image
The image to display in the widget. The value should be a
PhotoImage, BitmapImage, or a compatible object. If specified, this
takes precedence over the text and bitmap options. (image/Image)
Right now you are just passing a string for image option of label. You need something like,
photo = PhotoImage(file="image.gif")
label = Label(..., image=photo)
label.photo = photo #reference keeping is important when working with images
Right now, since you are using PNG image, you need to install and use Python Imaging Library (PIL) though. For more info, you can read Photo Image section from effbot.

Python: Can't display images in Zelle graphics.py, tkinter can't read image data

I am trying to display the image "picture.gif" in this code:
from graphics import *
import tkinter
win = GraphWin("Self Portrait", "1000", "500")
image = Image(Point(5,5), "picture.gif")
image.draw(win)
window.mainloop()
However, I keep getting this error:
Traceback (most recent call last):
File "/Users/jstorrke/Desktop/Python/graphicsProject.py", line 6, in <module>
image = Image(Point(5,5), "picture.gif")
File "/Users/jstorrke/Desktop/Python/graphics.py", line 827, in __init__
self.img = tk.PhotoImage(file=pixmap[0], master=_root)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 3394, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 3350, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "picture.gif"
The graphics module provides very minimal support for displaying images. Try putting the image on the same folder as where graphics library is and see if it helps.
Please look at this document for more information on graphics module. http://mcsp.wartburg.edu/zelle/python/graphics/graphics.pdf
_tkinter.TclError: couldn't recognize data in image file "picture.gif"
I looked at dozens of examples this error message and the cause seems to fall into two categories:
1) The file wasn't a supported type (e.g. *.jpg, *.png, *.tif) which was obvious from the extension.
2) The file used was mislabeld as a *.gif when it wasn't. (More common than I would expect.) On Unix systems you may be able to use the file command to verify your GIF:
> file p7Q6O.gif
p7Q6O.gif: GIF image data, version 89a, 520 x 416
>
An actual failure of a valid GIF file occurs if it's an animated GIF which are not supported. However, this can be a silent failure -- no error message and no image displayed.

Importing image into Tkinter - Python 3.5

I'm majorly struggling to import an image into Tkinter for Python 3.5, this is for my A2 project and have hit a brick wall with every method of importing a .JPG file to my window. What I have below is my GUI layer for another window, based off another thread I found but didn't work at all. Any assistance appreciated.
import tkinter
from tkinter import *
root=Tk()
root.geometry('1000x700')
root.resizable(False, False)
root.title("Skyrim: After Alduin")
photo = PhotoImage(file="Skyrim_Map")
map=Label(root, image=photo)
map.photo=photo
map.pack()
root.mainloop()
Here's the error I receive:
Traceback (most recent call last):
File "E:\Programming\Text_Adventure_Project\GUI_Interface-S_AA.py", line 14, in <module>
photo = PhotoImage(file="Skyrim_Map")
File "C:\Users\Harrison\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 3393, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Users\Harrison\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 3349, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "Skyrim_Map": no such file or directory
First check the path if with the correct path still persist the error "no such file or directory" please edit and put the newest version of your code.
If the error is "couldn't recognize data in image file" you can correct using PIL
[...]
from PIL import ImageTk
[...]
photo = ImageTk.PhotoImage(file='Skyrim_Map.jpg')
[...]
Try this:
from PIL import Image , ImageTk
img = Image.open("your_img")
image = ImageTk.PhotoImage(img)
An other point of view :
class Application:
...
self.photo=PhotoImage(file='picture.gif')
self.item=self.can.create_image(200, 100, image=self.photo)
...
Hope to help ! ;)

Where do I store image that I am going to use in my python script?

I am trying to render an image in tkinter. I have seen many scripts on stack overflow on how to make an image, but when I try that it says that my picture does not exist. Is there a certain place where I have to store my image? My python script is saved to the desktop, but I know that python may not search there. Where do I put the image that I want to show in my program? Thanks in advance!
Edit: Here is requested code:
canvas = Canvas(app, width=300, height=250).pack()
picture = PhotoImage(file='image.gif') #image located in desktop
canvas.create_image(0,0, image = picture
Here is the error:
Traceback (most recent call last):
File "/Users/theroeloffs/Downloads/myprogram.py", line 87, in <module>
piper_pic=PhotoImage(file = 'image.gif')
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 3306, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 3262, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
TclError: couldn't open "image.gif": no such file or directory
sorry for some reason this website wouldn't let me make that code
P.S. I have a mac
Just put it in the same file as your script.
Hope that helps!
You can use absolute path to it:
picture = PhotoImage(file='/Users/theroeloffs/Desktop/image.gif')
Or the better version is, to copy your image to this location:
/Users/theroeloffs/Downloads/image.gif
(where your script is) and than you can use the file name only:
picture = PhotoImage(file='image.gif')

Categories