Display an Image on Tkinter Window in Another Function

Introduction

A few days ago from the day I'm writing this article, an idea came to my mind; to create an image rotator application using python. In this project, I was trying to display an image on the Tkinter window by calling another function. It was necessary to perform, otherwise, I couldn't build that application. But the problem arises when I try to run that program, the image was vanishing from the main window.

I rechecked my code but, didn't find any wrong. Then, the problem gets in my hand. Python garbage collector removes the memory occupied by the variables when they are no longer in use(it generally happens when we leave a function, the variables declares in there are released by the garbage collector). I've found a tricky solution to avoid this problem.

Solution

Suppose, I want to display this 'cat.jpg' image on the Tkinter window. We need to declare a variable with a 'None' value at the very first and make it global in the outer function(in my case, 'show_image') function.

Code


from tkinter import *
from PIL import ImageTk, Image

img = None

def show_image():
global img

image = Image.open('cat.jpg')
resized_image = image.resize((740, 480))

img = ImageTk.PhotoImage(resized_image)

# Create a Label Widget to display the Image
label = Label(frame, image=img)
label.pack()

if __name__ == '__main__':
window = Tk()
window.geometry("960x600")
window.title('Display Image')

frame = Frame(window, width=740, height=480)
frame.pack()
frame.place(anchor='center', relx=0.5, rely=0.5)

show_image()

window.mainloop()

Output

display an image on tkinter window in another function using pillow module

Subhankar Rakshit

Meet Subhankar Rakshit, a Computer Science postgraduate (M.Sc.) and the creator of PySeek. Subhankar is a programmer, specializes in Python language. With a several years of experience under his belt, he has developed a deep understanding of software development. He enjoys writing blogs on various topics related to Computer Science, Python Programming, and Software Development.

Post a Comment (0)
Previous Post Next Post