0

when I write the canvas creation inside the definition, then it won't show any image. Though writing it out of definition, it works well. I do not why, and I want it inside the definition: here is the code.

import cv2
import tkinter as tk
from PIL import Image, ImageTk

def gettkimage():
    new_image_path = "tmp.jpg"
    image_bgr = cv2.imread(new_image_path)
    image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
    image_pil = Image.fromarray(image_rgb) # convert to PIL
    image_tk = ImageTk.PhotoImage(image_pil, master=root)
    return image_tk

def createimage():
    new_image_path = "tmp.jpg"
    image_bgr = cv2.imread(new_image_path)
    image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
    image_pil = Image.fromarray(image_rgb) # convert to PIL
    image_tk = ImageTk.PhotoImage(image_pil, master=root)
    canvas.create_image(0,0, image=image_tk, anchor='nw')

#works well
root = tk.Tk()
canvas = tk.Canvas(root, width=500, height=200) #create canvas
canvas.pack()
img_tk = gettkimage() #get image as a tkinter format
canvas.create_image(0,0, image=img_tk, anchor='nw')
root.mainloop()

'''
#not work
root = tk.Tk()
canvas = tk.Canvas(root, width=500, height=200) #create canvas
canvas.pack()
createimage() #attempting to create the image defined above
root.mainloop()
'''

I have no idea what causes the problem. I would appreciate your help.

Ted
  • 63
  • 7
  • 2
    Read [Why does Tkinter image not show up if created in a function?](https://stackoverflow.com/a/16424553/7414759) – stovfl Apr 04 '19 at 08:50
  • Exactly the same problem he had too. Now I understand why. Thank you very much! – Ted Apr 04 '19 at 13:05

0 Answers0