[Image-SIG] PIL and Tk PhotoImage

Nick Bower nick@nickbower.com
Tue, 16 Jan 2001 01:53:29 GMT


Mark,

There's a little more to it than this (unless it changed for Python 2.0)=
.=20
 PhotoImage is a Tk widget, so must be considered in this framework, not=
=20
out on its own like your example program.

I got the same error as you have when figuring this all out, but solved =

it by playing around with the order of creating a photoimage, canvas,=20
etc.

Below is the starting section of code of a Tk Viewport object I use in=20
the Python Data Language (PyDL).  You can play around with the order of =

things.  You'll notice I'm not supplying the PIL image to PhotoImage on =

construction, but instead later after it has been embedded in a canvas. =
=20
I can't remember whether you can do the former.

nick=20


class TkViewport(Frame):

  def __init__(self, parent, xsize, ysize, title):
  =20
    self.toplevel =3D parent
    self.xsize =3D xsize
    self.ysize =3D ysize
    self.hasdata =3D 0

    Frame.__init__(self, parent)
    self.pack()

    self.master.title(title)

    self.imagecanvas =3D Canvas(self, width=3Dxsize, height=3Dysize)
    self.imagecanvas.pack(side=3DBOTTOM)

    self.tkimage =3D ImageTk.PhotoImage('P',(self.xsize,self.ysize))
   =20
self.imagecanvas.create_image(self.xsize/2,self.ysize/2,image=3Dself.tki=
ma
ge)

then later...

    self.tkimage.paste(Image.new('P',(400,400)))





>>>>>>>>>>>>>>>>>> Original Message <<<<<<<<<<<<<<<<<<

On 1/16/01, 8:32:45 AM, mark brady <brady@mmm.com> wrote regarding=20
[Image-SIG] PIL and Tk PhotoImage:


> The following simple program is supposed to read an image
> using PIL and then convert it into a Tkinter PhotoImage (Running
> on a Mac):

>    from Image import *
>    from Tkinter import *

>    im =3D open("lena.jpg")
>    im.load()
>    tkIm =3D PhotoImage(im)

> Instead, it chokes on the last line, giving the following error messag=
e:

>    Traceback (most recent call last):
>        File "Macintosh HD:Applications:Python 2.0:MyToys:MakeTkImage",=
=20
line
> 6, in ?
>            tkIm =3D PhotoImage(im)
>        File "macintosh hd:applications:python 2.0:lib:lib-tk:Tkinter.p=
y",
> line 2974, in __init__
>            apply(Image.__init__, (self, 'photo', name, cnf, master), k=
w)
>        File "macintosh hd:applications:python 2.0:lib:lib-tk:Tkinter.p=
y",
> line 2915, in __init__
>            raise RuntimeError, 'Too early to create image'
>        RuntimeError: Too early to create image

> Why is it too early to create the image?

> -Mark


> _______________________________________________
> Image-SIG maillist  -  Image-SIG@python.org
> http://mail.python.org/mailman/listinfo/image-sig