让Tkinter暂停一秒

时间:2018-05-06 00:01:36

标签: python-3.x tkinter delay

我试图使用tkinter构建一个简单的photobooth类型应用程序。我认为我有我想要的东西,除了tkinter实际上暂停(照片拍摄倒计时)时应该。

这是一个准确的例子:

import tkinter as tk

class Photobooth:
    def __init__(self, master):
        self.master = master
        master.title('Photo Booth')
        self.seconds = 3
        self.secs = 3
        self.num_photos = 0

        self.display = tk.Label(master, height=20, width=60, textvariable="")
        self.display.config(text='Photobooth!')
        self.display.grid(row=0, column=0, columnspan=1)

        self.three_photo_button = tk.Button(master,
                                            bg='Blue',
                                            activebackground='Dark Blue',
                                            text='Take 3 Photos',
                                            width=60,
                                            height=8,
                                            command=lambda: self.take_photos(3))
        self.three_photo_button.grid(row=1, column=0)

    def tick(self):
        # Need a dummy function to pause with.
        pass

    def take_photos(self, num_photos):
        self.secs = self.seconds
        # Cycle through each photo
        for n in range(num_photos):
            # Cycle through countdown timer
            for s in range(self.seconds):
                # Display seconds left
                self.display.config(text='{}'.format(self.secs))

                if self.secs == 0:
                    # "Take photo" by displaying text
                    self.display.config(text='Took {} of {} photos!'.format(n, num_photos))
                    # Wait a fraction of a second, then continue.
                    self.master.after(100, self.tick)
                    # Except if we are at our photo limit, then show: 'Done'.
                    if n == (num_photos - 1):
                        self.display.config(text='Done!')
                        self.master.after(100, self.tick)
                else:
                    # Decrease timer
                    self.secs -= 1
                    # Wait one second
                    self.master.after(1000, self.tick)

if __name__ == '__main__':
    root = tk.Tk()
    my_timer = Photobooth(root)
    root.mainloop()

当我运行应用程序时,它似乎工作,但一切都运行得太快(没有暂停)。我是tkinter的新手,但是after()函数应该让应用程序循环暂停,但它似乎并没有这样做。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

这可以让你知道如何思考:

def take_photos(self,num_photos):
    for i in range(num_photos):
        delay = (i+1) * 1000
        self.master.after(delay, self.take_one_photo, i+1, num_photos)

def take_one_photo(self,n,m):
    # "Take photo" by displaying text
    self.display.config(text='Took {} of {} photos!'.format(n, m))