[Tutor] Python Image Library
Peter Otten
__peter__ at web.de
Fri May 19 10:15:23 EDT 2017
Alan Gauld via Tutor wrote:
> On 18/05/17 18:06, Alan Gauld via Tutor wrote:
>
>> Here is some untested Tkinter code to display an image
>> for 2 seconds:
>
> I tried this last night and it turned out to be harder
> than I expected. Eventually I got to bed at 3am! But here
> is something that seems to work for jpegs. I hope bmp files
> will too, I didn't have any to test...
>
> #################################################
> import tkinter as tk
> from PIL import Image,ImageTk
>
> def showImage(imgName, delay=2000, wd=400, ht=400):
> '''Display the file imgName
> for delay milliseconds
> in a window sized wd x ht
> Close the window afterwards'''
>
> top = tk.Tk()
> top.withdraw() # hide the root window
> win = tk.Toplevel()
> PILimage = Image.open(imgName)
> TKimg = ImageTk.PhotoImage(PILimage)
> tk.Label(win, image=TKimg, width=wd, height=ht).pack()
> top.after(delay, lambda : (win.withdraw(), top.quit()) )
> top.mainloop()
>
>
> ############## Test code #########
> import glob,os
>
> root = r"/full/path/to/your/files"
>
> for filename in glob.glob(root + "/*.jpg"):
> print(filename)
> showImage(filename)
I found your original sketch a bit more appealing and went to explore why it
didn't work. The problem you already have fixed is passing a PhotoImage to
the Label instead of the filename. The other seems to be that you need to
call the destroy() rather than the quit() method. At least the following
works on my Linux system, with jpegs:
def show_image(imagename, delay=2000, width=None, height=None):
root = tk.Tk()
image = ImageTk.PhotoImage(Image.open(imagename))
tk.Label(root, image=image, width=width, height=height).pack()
root.after(delay, root.destroy)
root.mainloop()
However, as your code gets away without calling destroy() I'm still
puzzled...
More information about the Tutor
mailing list