Python Tkinter time.sleep()

时间:2016-01-12 19:12:12

标签: python tkinter

我正在制作一个节目,但我遇到了问题。当使用time.sleep()时,就像它在代码中显示的一样,我希望它在第一个标签出现后等待5秒,然后显示第二个标签,但是当我按下“开始”按钮时它等待5秒然后一次显示两个标签。 (我感兴趣的代码就在最后,guess_number

以下是代码:

from tkinter import *
from tkinter import font
from datetime import datetime
import time

class Window(Frame):

    def __init__(self, master):

        Frame.__init__(self, master)
        self.master = master
        self.master.resizable(0,0)
        master.title("Arcade Games")
        master.geometry("800x600+560+240")
        now = datetime.now()
        hour = now.hour
        minutes = now.minute
        b = Button(self, text="Guess the number", command=self.new_window,      cursor='hand2', relief='groove')
        b.pack()
        self.customFont = font.Font(master, font="Heraldica", size=12)
        labelTime = Label(self.master, text=str(hour)+" : "+str(minutes), font=self.customFont)
        labelTime.pack(side='bottom')


    def new_window(self):

        id = "Welcome to the 'Guess your number' game!\nAll you need to do is follow the steps\nand I will guess your number!\n\nClick the button to start!!"
        self.window = Toplevel(self.master)
        self.window.resizable(0,0)
        self.label = Label(self.window, text=id, font=self.customFont)
        self.label.pack(side="top", fill="both", padx=20, pady=20)
        self.button = Button(self.window, text="Start", relief='groove')
        self.button.config(width=20, height=2)
        self.button.bind("<Button-1>", self.guess_number)
        self.button.pack()
        self.window.title("Guess the number")
        self.window.geometry("400x300+710+390")

    def guess_number(self, event):

        self.button.destroy()
        self.label.destroy()
        labelGuess = Label(self.window, text="Pick any number.\nIt can be 3, 500 or even 1,324,324", font=self.customFont)
        labelGuess.pack(padx=20, pady=20)
        time.sleep(5)
        labelGuess1 = Label(self.window, text="Now double it", font=self.customFont)
        labelGuess1.pack(padx=20, pady=20)


if __name__ == "__main__":
    root = Tk()
    view = Window(root)
    view.pack(side="top", fill="both")
root.mainloop()

感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

不要使用time.sleep()来停止主要任务,而是尝试使用tkinter after()安排一个事件,如下所示:

def guess_number(self, event):
    self.button.destroy()
    self.label.destroy()
    labelGuess = Label(self.window, text="Pick any number.\nIt can be 3, 500 or even 1,324,324", font=self.customFont)
    labelGuess.pack(padx=20, pady=20)
    self.window.after(5000, self.make_guess1_visible)

def make_guess1_visible(self):
    labelGuess1 = Label(self.window, text="Now double it", font=self.customFont)
    labelGuess1.pack(padx=20, pady=20)