Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() 
like image 587
thomas.winckell Avatar asked May 07 '13 16:05

thomas.winckell


People also ask

Why is tkinter not showing image?

When you add a PhotoImage or other Image object to a Tkinter widget, you must keep your own reference to the image object. If you don't, the image won't always show up.

Does tkinter work with JPG?

Images can be shown with tkinter. Images can be in a variety of formats including jpeg images. A bit counterintuitive, but you can use a label to show an image.

What image types does tkinter support?

Tkinter PhotoImage only supports the GIF, PGM, PPM, and PNG file formats. Use the PhotoImage widget from the PIL.


2 Answers

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:

Why do my Tkinter images not appear? (The FAQ answer is currently not outdated)

like image 156
Bryan Oakley Avatar answered Sep 18 '22 05:09

Bryan Oakley


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

like image 30
TIRTH SHAH Avatar answered Sep 21 '22 05:09

TIRTH SHAH