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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With