Hello

I'm quite new to Python and would require some advice. I'm trying to create a picture viewer that changes pictures with regular intervals.
The problem arises when I try to use time.sleep() along my go(), which changes the image.
The code first loads images from a folder and uses go() to change the image. go() is executed by keyEvent().

The code:

File reading
def loadImages():
    global pixbufs
    for file in os.listdir(dir):
        filePath=os.path.join(dir, file)
        pix=gtk.gdk.pixbuf_new_from_file(filePath)
        pix=scaleToBg(pix, bg)
        pixbufs.append(pix)
        print("Loaded image "+filePath) 
Controls
def go(relativePos):
    global pos
    pos+=relativePos

    last=len(pixbufs)-1
    if pos<0:
        pos=last
    elif pos>last:
        pos=0

    image.set_from_pixbuf(pixbufs[pos])

def keyEvent(widget, event):
    global pos, image
    key = gtk.gdk.keyval_name(event.keyval)
    if key=="space" or key=="Page_Down":
        go(1)
        time.sleep(5)
        go(1)
    elif key=="b" or key=="Page_Up":
        go(-1)
    elif key=="q" or key=="F5":
        gtk.main_quit()
    else:
        print("Key "+key+" was pressed")

So, the problem is in the keyEvent() part, where the execution order after pressing "space" is not the one I want. For instance, if I want to change image, wait 5s and change image again, I write:

go(1)
time.sleep(5)
go(1)

but the result is the same as writing:

time.sleep(5)
go(1)
go(1)

The problem seems to be that the time.sleep() is always executed before go() regardless of the writing order in the code. I tried to run the code unbuffered, but it didn't help. How do I get Python to perform the commands in the order that I want? The final program should use a set of pictures and show each picture for a few seconds in a loop. Using a for loop:

for i in range(4):
    time.sleep(5)
    go(1)
    i=i+1

the same problem is present, the code acts as:

time.sleep(20)
go(4)

How do I get this fixed?
Thank you in advance
-Kerma

Recommended Answers

All 5 Replies

Use after timer style of event. I do not know exactly how you do that in gtk.

Thank you for your reply. I have looked into the use of after method, but no breakthrough so far. Guess I have to study some more.

Timeout_add does not seem to allow one to simply add waiting times like I was actually expecting when I tried to use the time.sleep method. Like if the waiting times differ: wait 4 sec, run next line, wait 5 sec, run next line. One can solve this by adding a timeout_add inside a timer, which does not seem very practical, but it works. Nonetheless, with timeout_add I can easily produce a slide show with constant transitions.
Thank you for the solution.

Take a look at chapter 19 in the official pygtk tutorial.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.