PNG images in PhotoImage labels
Joal Heagney
s713221 at student.gu.edu.au
Wed Aug 8 06:25:38 EDT 2001
moonlite56 at yahoo.com wrote:
>
> I am learning Python this summer, and kind of ran into a rut when I
> tried to display .png images in a simple label test. This is what I
> have so far:
>
> from Tkinter import *
>
> top = Tk()
> top.title("Kuti")
> top.geometry("200x100")
>
> iKuti = PhotoImage(file = "gameboy.png")
> lHello = Label(top, image = iKuti)
> lHello.grid(row = 1, col = 1, sticky = W)
> bQuit = Button(top, text="Quit", command = top.quit)
> bQuit.grid(row = 1, col = 2, sticky = E)
>
> top.mainloop()
>
> This works with gameboy.gif, but gameboy.png displays an error:
>
> Traceback (most recent call last):
> File "tkinter.py", line 9, in ?
> iKuti = PhotoImage(file = "gameboy.png")
> File "/usr/lib/python2.0/lib-tk/Tkinter.py", line 2974, in __init__
> apply(Image.__init__, (self, 'photo', name, cnf, master), kw)
> File "/usr/lib/python2.0/lib-tk/Tkinter.py", line 2930, in __init__
> self.tk.call(('image', 'create', imgtype, name,) + options)
> TclError: couldn't recognize data in image file "gameboy.png"
>
> How do I get this to work with PNG images?
This is because the underlying tcl/tk (if it is standard tk) only
recognises gifs, *hunts for reference book* pgm and ppm formats. You can
use png's if you install the python imaging library (PIL). With PIL
installed, do the following (After you've created a Tk instance or you
get a RuntimeError returned on the second line.):
import Image,ImageTk
iKuti = ImageTk.PhotoImage(Image.open("gameboy.png"))
# You're using Image.open("gameboy.png") instead of the file =
"gameboy.png" bit.
Isn't Tkinter cool?!!!
--
Joal Heagney is: _____ _____
/\ _ __ __ _ | | _ ___ |
/__\|\ || ||__ |\ || |___|/_\|___] |
/ \ \_||__ ||___| \_|! | | \ \ !
More information about the Python-list
mailing list