当代码位于def内部时,canvas.create_image不起作用:

时间:2019-04-04 08:21:52

标签: python tkinter-canvas

当我在定义中编写画布创建时,它将不会显示任何图像。 尽管无法定义,但效果很好。 我不为什么,我想在定义中使用它: 这是代码。

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()
'''

我不知道是什么原因引起的。 感谢您的帮助。

0 个答案:

没有答案