Why does Tkinter image not show up if created in a function?

Posted on

Solving problem is about exposing yourself to as many situations as possible like Why does Tkinter image not show up if created in a function? and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about Why does Tkinter image not show up if created in a function?, which can be followed any time. Take easy to follow this discuss.

Why does Tkinter image not show up if created in a function?

This code works:

import tkinter
root = tkinter.Tk()
canvas = tkinter.Canvas(root)
canvas.grid(row = 0, column = 0)
photo = tkinter.PhotoImage(file = './test.gif')
canvas.create_image(0, 0, image=photo)
root.mainloop()

It shows me the image.

Now, this code compiles but it doesn’t show me the image, and I don’t know why, because it’s the same code, in a class:

import tkinter
class Test:
    def __init__(self, master):
        canvas = tkinter.Canvas(master)
        canvas.grid(row = 0, column = 0)
        photo = tkinter.PhotoImage(file = './test.gif')
        canvas.create_image(0, 0, image=photo)
root = tkinter.Tk()
test = Test(root)
root.mainloop()

Answer #1:

The variable photo is a local variable which gets garbage collected after the class is instantiated. Save a reference to the photo, for example:

self.photo = tkinter.PhotoImage(...)

If you do a Google search on “tkinter image doesn’t display”, the first result is this:

http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm

Answered By: Bryan Oakley

Answer #2:

Just add global photo as the first line inside the function.

Answered By: Gabriel

Answer #3:

from tkinter import *
from PIL import ImageTk, Image
root = Tk()
def open_img():
    global img
    path = r"C:.....\"
    img = ImageTk.PhotoImage(Image.open(path))
    panel = Label(root, image=img)
    panel.pack(side="bottom", fill="both")
but1 = Button(root, text="click to get the image", command=open_img)
but1.pack()
root.mainloop()

Just add global to the img definition and it will work

Answered By: TIRTH SHAH
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.