-1

It seems to be a very common application, but I could not make it work:

def Img2Canvas(Img,Canv): # this function will put image on a canvas by stretching it

Canv.update()
H=Canv.winfo_height()
W=Canv.winfo_width()
print([W,H])

temp=ImageTk.PhotoImage(Img.resize((W,H)))
Canv.create_image(1,1,anchor=tk.NW,image=temp)

Then I called this function in main program:

cv1=tk.Canvas(root,width=200,height=200,bg='yellow')
Img2Canvas(p1.Img,cv1)

1) this does not work, The canvas is not updated, and I just got a Yellow background. It only works if I do not do temp=ImageTk.PhotoImage(Img.resize((W,H))) inside the function, but resize the image outside of function and input temp directly...

2) the W and H seems to be 204 instead of 200, so is winfo_height() always give you 4 more pixels?

3) is there a better way to display a figure file (jpg, png, etc.) in Tkinter?

spee
  • 1

1 Answers1

1

You need to keep a reference to the image temp as it is a local variable which will be garbage collected after the function ends. Suggest to return temp and assign it to a variable:

def Img2Canvas(Img, Canv):
    ...
    return temp

...
tkimg = Img2Canvas(p1.Img, cv1)

The extra pixels in the width and height is the size of highlightthickness, set it to 0 when creating the canvas:

cv1 = tk.Canvas(root, width=200, height=200, highlightthickness=0, bg='yellow')
acw1668
  • 40,144
  • 5
  • 22
  • 34
  • Thanks a lot, acw1668. But if I just want the Img2Canvas function to update Canvas, once it does that, I dont really care to keep a copy of temp.... Whether I keep temp in memory or not, cv1 should be updated already, right? or it will be flushed blank if temp is gone? – spee May 19 '20 at 02:15
  • The image will be lost if `temp` is garbage collected. – acw1668 May 19 '20 at 02:21
  • Or you can replace the line `return temp` to `Img.tkimg = temp` to keep the reference. – acw1668 May 19 '20 at 02:25
  • I see. I used to use temp to update Widgets like button's text or color of something, then garbage the temp when exiting function. It looks like Canvas does not store the displaced Image within itself, it is just a reference. so when temp is out, Canvas has nothing to show... Great! I got it to work and thanks a lot for the help!!! – spee May 19 '20 at 17:31