How to add all images from a folder to a button (in my frame) [closed]
I want to store .jpg
images from a folder in an array, and than use them to add it to a buttons in my frame of Python.
I am using tkinter and PIL library in Python 3.4.3 .I am using windows 8.1 os I want to load the image for a folder with few lines of code and I also element border of the grid to show them like a single image
Below is some code to get you started.
To simplify testing I wrote a small program that uses PIL to generate colored squares and saves them to a folder. I tested these programs using Python 2.6.6 on Linux. They should work on Python 3, (assuming Tkinter & PIL are installed properly on your system) but you will need to change import Tkinter as tk
toimport tkinter as tk
in tk_frame_grid.py.
This program generates 30 colored squares, saving them to the 'squares' folder in the current directory. You need to create 'squares' before running the program.
PIL_2colorsquares.py
#! /usr/bin/env python
''' Create squares that fade from one color to another & save
Written by PM 2Ring 2015.07.18
'''
from PIL import Image
from itertools import permutations
def color_squares(size, colorpairs, basename, ftype):
#Make the composition mask
m = 255.0 / (2 * size - 2)
r = range(size)
mask = Image.new('L', (size, size))
mask.putdata([int(m * (x + y)) for y in r for x in r])
for count, (c0, c1) in enumerate(colorpairs):
im0 = Image.new('RGB', (size, size), color=c0)
im1 = Image.new('RGB', (size, size), color=c1)
im = Image.composite(im0, im1, mask)
im.save('%s%03d%s' % (basename, count, ftype))
def main():
size = 64
colors = ('red', 'yellow', 'green', 'cyan', 'blue', 'magenta')
colorpairs = permutations(colors, 2)
basename = 'squares/sq'
ftype = '.png'
color_squares(size, colorpairs, basename, ftype)
if __name__ == '__main__':
main()
This program first fills a list with PIL images, using image files from a named directory; these images can be in any file format that PIL can read. It then creates a Tkinter window containing a Frame that holds a grid of Buttons using the images. There is no error checking, so don't put non-image files into the 'squares' folder.
You need to specify the grid dimensions. If there aren't enough images to fill the grid you will get a StopIteration
error.
tk_frame_grid.py
#!/usr/bin/env python
''' Create a grid of Tkinter Buttons with PIL images in a Frame
See http://stackoverflow.com/q/31489121/4014959
Written by PM 2Ring 2015.07.18
'''
from __future__ import print_function
import os
import Tkinter as tk
from PIL import Image, ImageTk
class FrameDemo(object):
''' A Frame containing a grid of image Buttons '''
def __init__(self, rows, columns, images):
images = iter(images)
master = tk.Tk()
master.title("Image Buttons in a Frame")
frame = tk.Frame(master)
frame.pack()
for y in range(rows):
for x in range(columns):
#Get the next image from the list and
#convert it to a TK Photo object
name, img = next(images)
photo = ImageTk.PhotoImage(img)
#Create the button & put it in the Frame
b = tk.Button(frame, image=photo)
b.grid(row=y, column=x)
#Add a call-back function
func = lambda t=name: self.button_cb(t)
b.config(command=func)
#We have to save a reference to the photo or it gets
#garbage-collected, so we attach it as a button attribute
b.photo = photo
master.mainloop()
def button_cb(self, name):
print("'%s' button pressed" % name)
def main():
image_folder = 'squares'
#Load all files in image_folder as PIL images
#and put them into a list
images = [(name, Image.open(os.path.join(image_folder, name)))
for name in sorted(os.listdir(image_folder))]
gui = FrameDemo(rows=5, columns=6, images=images)
if __name__ == '__main__':
main()