image resize doesn't work

Peter Otten __peter__ at web.de
Sun Aug 1 17:32:56 EDT 2010


Chris Hare wrote:

> Thanks for the help.  My one week of python is getting a workout.
> 
> I have shortened it all down and made it a standalone example, using yours
> as a model.  Your example, works, but it will take a lot of effort to
> retrofit it into the code I have.  (which is maybe not a bad idea,).

You mean retrofit something that works into something tha doesn't?
Seriously, you should never be afraid to throw away code, especially while 
you're still in the early phase of learning the language.

> def sizeit(filename):
>         image = Image.open(filename)

Now you have an Image

>         w,h = image.size
>         print w, h
>         photo = ImageTk.PhotoImage(file=filename)

and now a photo, both created from the same file but otherwise independent

>         canvasWidth = 450
>         canvasHeight = 412
>         image = image.resize((canvasWidth,canvasHeight),Image.ANTIALIAS)

Now you have a new resized Image

>         w,h = image.size
>         print w, h
>         netRadarImage = Label(frame, image=image)

Label(image=...) expects a PhotoImage

>         netRadarImage.image = photo
>         w.grid(row=1, column=0, columnspan=3)

Hmm...

>         netRadarImage.grid( row=1, column=0)

Here's the fixed code:

def sizeit(filename):
    image = Image.open(filename)
    canvasWidth = 450
    canvasHeight = 412
    image = image.resize((canvasWidth, canvasHeight),Image.ANTIALIAS)
    photo = ImageTk.PhotoImage(image=image)
    netRadarImage = Label(frame, image=photo)
    netRadarImage.image = photo
    netRadarImage.grid(row=0, column=0)

In plain English:

- open the Image using the PIL
- resize it
- wrap it into a PhotoImage
- wrap the PhotoImage into a Tkinter.Label either by passing it to the 
initialiser or by assigning to label["image"]
- make sure the PhotoImage isn't garbage-collected e. g. by assigning to 
label.image

Peter



More information about the Python-list mailing list