Выйти из Tks mainloop в Python? - PullRequest
       11

Выйти из Tks mainloop в Python?

1 голос
/ 29 апреля 2010

Я пишу программу слайд-шоу с Tkinter, но я не знаю, как перейти к следующему изображению без привязки ключа.

import os, sys
import Tkinter
import Image, ImageTk
import time

root = Tkinter.Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.overrideredirect(1)
root.geometry("%dx%d+0+0" % (w, h))
root.focus_set()

root.bind("<Escape>", lambda e: e.widget.quit())

image_path = os.path.join(os.getcwd(), 'images/')
dirlist = os.listdir(image_path)

for f in dirlist:
    try:
        image = Image.open(image_path+f)
        tkpi = ImageTk.PhotoImage(image)        
        label_image = Tkinter.Label(root, image=tkpi) # ?
        label_image.place(x=0,y=0,width=w,height=h)
        root.mainloop(0)
    except IOError:
        pass
root.destroy()

Я бы хотел добавить time.sleep (10) вместо root.mainloop (0), чтобы он перешел к следующему изображению через 10 секунд. Теперь это меняется, когда я нажимаю ESC. Как я могу иметь таймер там?

edit: я должен добавить, что я не хочу другой поток, который спит, даже если он работает.

Ответы [ 2 ]

5 голосов
/ 03 мая 2010

Нет необходимости делать цикл над изображениями - вы уже работаете в цикле (mainloop), так что воспользуйтесь этим. Типичный способ сделать это - создать метод, который рисует что-то, ждет некоторое время, а затем вызывает сам себя. Это не рекурсия, это просто говорит основной цикл «через N секунд, позвони мне снова».

Вот рабочий пример:

import glob
import Tkinter

class Slideshow:
    def __init__(self, pattern="*.gif", delay=10000):

        root = Tkinter.Tk()
        root.geometry("200x200")

        # this label will be used to display the image. Make
        # it automatically fill the whole window
        label = Tkinter.Label(root) 
        label.pack(side="top", fill="both", expand=True)

        self.current_image = None
        self.image_label = label
        self.root = root
        self.image_files = glob.glob(pattern)
        self.delay = delay # milliseconds

        # schedule the first image to appear as soon after the 
        # the loop starts as possible.
        root.after(1, self.showImage)
        root.mainloop()


    def showImage(self):
        # display the next file
        file = self.image_files.pop(0)
        self.current_image = Tkinter.PhotoImage(file=file)
        self.image_label.configure(image=self.current_image)

        # either reschedule to display the file, 
        # or quit if there are no more files to display
        if len(self.image_files) > 0:
            self.root.after(self.delay, self.showImage)
        else:
            self.root.after(self.delay, self.root.quit)

    def quit(self):
        self.root.quit()


if __name__ == "__main__":
    app=Slideshow("images/*.gif", 1000)
5 голосов
/ 29 апреля 2010

Вы можете попробовать

root.after(10*1000, root.quit)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...