Tk window and contents will not display

Peter Otten __peter__ at web.de
Sat Aug 14 16:14:22 EDT 2010


Chris Hare wrote:

> The scenario is this:
> 
> I want to loop around all of the images in a given directory (which I know
> will be images, but I guess I should check), show an image in a window,
> wait 2 seconds and show the next one and repeat that indefinitley, which
> will be until the user closes the window.
> 
> This is the code I extracted from the larger program and made work - sort
> of - in a standalone fashion.  When I run the code, each of the file names
> gets displayed, and I can view the images, so it has to be something I am
> doing wrong with this chunk of code.
> 
> However, I don't see what the problem is.

I have not looked at your code in detail, but event loops and time.sleep() 
don't play together very well. Use after(delay_in_milliseconds, callable) 
instead. 

Here's a simple example that loops over images passed from the command line:

import Image
import ImageTk
import os
import sys
import Tkinter as tk

from itertools import cycle

def next_image():
    imagefile = next(imagefiles)
    image = Image.open(imagefile)
    
    w, h = image.size
    image = image.resize((700, 700*h//w))
    
    label.image = label["image"] = ImageTk.PhotoImage(image=image)
    root.title("Now showing %s" % os.path.basename(imagefile))
    
    root.after(2000, next_image)

if __name__ == "__main__":
    imagefiles = sys.argv[1:]
    assert imagefiles
    imagefiles = cycle(imagefiles)

    root = tk.Tk()
    label = tk.Label(root)
    label.pack()
    
    root.after_idle(next_image)
    root.mainloop()








More information about the Python-list mailing list