Local works, Instance fails


(michael libby) #1

I have written a TkSlide widget which essentially incorporates a conversion
routine (using ImageMagick’s convert tool) to get around the limitation of
TkPhotoImage needing either GIF or PPM images.

As you can see I set up a temporary pathname for the PPM file created by
convert. What’s odd is that in the TkSlide#show method, if I use the
instance variable @temp_file I don’t get an image, but if I assign it to a
local variable temp_file I do get an image.

Any thoughts? (And any notes on any place I can make my code better/more
idiomatic would also be appreciated as well…)

Thanks,

  • -michael

class TkSlide < TkLabel

def initialize(root, *args)
@root = root

#name for temp files
@temp_file = 'temp_pic_' + $$.to_s + '_' +
             rand(100000).to_i.to_s + '.ppm'
p "Temp file will be #{@temp_file}" if DEBUG

argh = args[0] || {}
@width = argh['width'] || @root.maxsize[0]
@height = argh['height'] || @root.maxsize[1]

super(@root, argh)

end

def show(pic_path)
@image.delete if @image #or suffer a memory leak
begin
#make sure file still exists
if !FileTest.exists?(pic_path)
p "#{pic_path} not found, aborting."
exit
end

  #convert to PPM and resize

#{CONVERT} -geometry #{@width}x#{@height} "#{pic_path}" ppm:#{@temp_file}
p “#{pic_path} converted” if DEBUG

  temp_file = @temp_file #for some reason @temp_file won't work in the 
  @image = TkPhotoImage.new{file temp_file} #image.new command!!
rescue
  p "Faulty image: #{$!}"
  exit
end
self.configure('image'=>@image)

#delete temp file immediately after use
File.delete(temp_file)

end
end


Michael_C_Libby{x(at)ichimunki(dot)com}__

···
      my website: http://www.ichimunki.com/           | 

____ public key at http://www.ichimunki.com/public.key ____|


(ts) #2

      temp_file = @temp_file #for some reason @temp_file won't work in the
      @image = TkPhotoImage.new{file temp_file} #image.new command!!

This is the way to do it, because if TkPhotoImage::new has a block it will
call #instance_eval.

This mean that with

    @image = TkPhotoImage.new{file @temp_file}

@temp_file make reference to an instance variable of the new TkPhotoImage
object

Guy Decoux