Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it shows blank instead of picture in my Tkinter program?

I want to use Tkinter to display all the pictures in a specific directory, so I firstly code to show all the pictures from a given list

The code is:

import os

from Tkinter import *
from PIL import Image, ImageTk

class Application(Frame):
    def add_pic_panel(self, pic):
        img = ImageTk.PhotoImage(Image.open(pic))
        label = Label(root, image = img)
        print label
        return label

    def create_gui(self):
        pics = ['1.jpg', '2.jpg']
        for pic in pics:
            self.add_pic_panel(pic)
        pass

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.create_gui()

root = Tk()
app = Application(master=root)
app.mainloop()
root.destroy()

Environment: Mac OS 10.9, Python 2.7.5 How could I display all the pictures in the list?

like image 502
Kane Blueriver Avatar asked Dec 28 '13 08:12

Kane Blueriver


People also ask

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

The gist of it is that the image is passed by reference. If the reference is to a local variable, the memory referenced gets reused and the reference becomes stale. The variable storing the image should be in the same scope (has to have the same lifetime) as the Tk gui object it appears on.

Does tkinter work with JPG?

Tkinter relies on Pillow for working with images. Pillow is a fork of the Python Imaging Library, and can be imported in a Python console as PIL. Pillow has the following characteristics: Support for a wide range of image file formats, including PNG, JPEG and GIF.

What to do if tkinter is not working?

In conclusion, if the error no module named tkinter raises, it probably means you are using python 2. Firstly, you can get around the problem by upgrading to python 3. Additionally, you can rename your import to Tkinter , which is how the module was named in python 2, just if upgrading is not an option.


1 Answers

  1. The code does not pack the label.
  2. Should keep the reference for the image.

def add_pic_panel(self, pic):
    img = ImageTk.PhotoImage(Image.open(pic))
    label = Label(self.master, image=img)
    label.img = img # to keep the reference for the image.
    label.pack() # <--- pack
    return label

BTW, add_pic_panel use root directly. It would be better to use self.master.

root.destroy() at the last line cause TclError when closing the window. Remove the line.

like image 63
falsetru Avatar answered Oct 06 '22 01:10

falsetru