Function to create Tkinter PhotoImages from directory?
James Stroud
jstroud at mbi.ucla.edu
Sun Jan 28 19:38:01 EST 2007
Kevin Walzer wrote:
> I am trying to create a number of Tk PhotoImages from a single
> directory. Currently I am hard-coding file names and image names, like so:
>
> def makeImages(self):
> self.imagedir = (os.getcwd() + '/images/')
> self.folder_new=PhotoImage(file=self.imagedir + 'folder_new.gif')
> self.save=PhotoImage(file = self.imagedir + 'save.gif')
> self.folder=PhotoImage(file=self.imagedir + 'folder.gif')
> self.help=PhotoImage(file=self.imagedir + 'help.gif')
> self.fontsmall=PhotoImage(file=self.imagedir + 'fontsmall.gif')
> self.stop=PhotoImage(file=self.imagedir + 'stop.gif')
>
> What I'd like to do is glob the directory and create images with the
> same name as the gif file, but I can't figure out how to get that to
> work. Can anyone help?
>
Should be (wrote setattr to fast):
def makeImages(self):
import glob
import os
self.imagedir = os.path.join(os.getcwd(), 'images')
pattern = os.path.join(self.imagedir, '*.gif')
image_names = glob.glob(pattern)
for name in image_names:
base = os.path.basename(name).split('.')[0]
pathname = os.path.join(self.imagedir, n)
setattr(self, base, Photoimage(file=pathname))
More information about the Python-list
mailing list