【问题标题】:Exit Tks mainloop in Python?在 Python 中退出 Tks 主循环?
【发布时间】:2010-04-28 20:22:03
【问题描述】:

我正在用 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 时它会改变。我怎么能在那里有一个计时器?

编辑:我应该补充一点,即使它可以工作,我也不希望另一个线程进入睡眠状态。

【问题讨论】:

标签: python tkinter tk


【解决方案1】:

你可以试试

root.after(10*1000, root.quit)

【讨论】:

  • 非常感谢!像魅力一样工作。
【解决方案2】:

无需对图像进行循环——您已经在循环中运行(主循环),因此请充分利用它。执行此操作的典型方法是创建一个绘制某些东西的方法,等待一段时间,然后调用自身。这不是递归,它只是告诉主循环“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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-15
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 2015-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多