Search code examples
pythonfunctiontkinter

python, function that shows image in tkinter?


i want to create a tkinter window and display the lena picture. I got a code that is working but i dont know how to make a function out of it.

code:

import numpy
import cv2
from Tkinter import *
from PIL import Image, ImageTk
import scipy.misc

#create root window
root = Tk()
root.geometry("600x600")

#path to lena picture
lena = "C:\lena.jpg"

##------------this as function----------------------------
#convert lena.jpg into tkinter photo image
image = Image.open(lena)
photo = ImageTk.PhotoImage(image)

#create canvas to display picture
w = Canvas(root)
w.create_image(0, 0, image = photo, anchor = "nw")
w.pack(fill = BOTH, expand = YES)
##-------end:-this as function----------------------------


#start root window
root.mainloop()

I tried this function but it didnt open the lena picture...:

#create root window
root = Tk()
root.geometry("600x600")

#path to lena picture
lena = "C:\lena.jpg"


def imgShow(img):
    ##------------this as function----------------------------
    #convert lena.jpg into tkinter photo image
    image = Image.open(img)
    photo = ImageTk.PhotoImage(image)

    #create canvas to display picture
    w = Canvas(root)
    w.create_image(0, 0, image = photo, anchor = "nw")
    w.pack(fill = BOTH, expand = YES)
    ##-------end:-this as function----------------------------

##use function with lena image path.
## doesnt work: window pops up but lena image is not shown
imgShow(lena)

#start root window
root.mainloop()

## ErrorMessages?: No Error Message 

Do you know what i am doing wrong?


Solution

  • There is well known problem with PhotoImage assigned to local variable in function.
    Garbage Collector removes image when you leave function
    but you can assign photo (for example) to w like this:

    photo = ImageTk.PhotoImage(image)
    
    w = Canvas(root)
    w.photo = photo  # assign photo to object.