image resize doesn't work

Chris Hare chare at labr.net
Mon Aug 2 00:11:57 CEST 2010


Thanks Peter - I know what I said sounded stupid :-)

I have been working with Python for a week and as you know sometimes it is easier to learn by seeing what you did wrong as compared to what should have been done with the same example.  I loved your code by the way - 

Thanks for help just another beginner ....


On Aug 1, 2010, at 4:32 PM, Peter Otten wrote:

> 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
> -- 
> http://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list