Time.sleep()函数的放置

时间:2016-07-23 18:42:41

标签: python time tkinter

我遇到的问题是在尝试使用time.sleep(3)在屏幕上保留第一个函数(StartUpScr)小部件3秒钟之后,然后删除屏幕上放置的所有小部件然后继续放置下一个功能(MenuScr)小部件。我成功地使用destroy()来删除第一个小部件并用第二个小部件替换它们,但出于某种原因在函数和主程序中的任何地方输入time.sleep(3)时,而不是第一个小部件小部件停留3秒然后被替换它会延迟程序的开始产生一个空白屏幕,然后快速闪过第一个屏幕到第二个屏幕。

from tkinter import *
import tkinter
import time



window = tkinter.Tk()                               
window.title("BINARY-SUMS!!!")                      
window.geometry("1000x800")                        
window.wm_iconbitmap('flower3.ico')                 
window.configure(background='lavender')            

def StartUpScr():
    StartUpScr = tkinter.Label(window, text="FIRST-SCREEN!!!",fg = "Aqua",bg = "Lavender",font = ("Adobe Gothic Std B", 90, "bold" )).pack()

StartUpLabel = tkinter.Label(window, text="Developed by Robert Bibb 2016",bg = "Lavender",font = ("Calibri Light (Headings)", 10, "italic" ))
    StartUpLabel.pack()
    StartUpLabel.place(x = 400, y = 775)


def MenuScr():
    StartUpScr = tkinter.Label(window, text="SECOND-SCREEN!!!",fg = "green",bg = "Lavender",font = ("Adobe Gothic Std B", 85, "bold" ))
    StartUpScr.pack()


if __name__ == "__main__":
    StartUpScr()
    time.sleep(3)
    for widget in window.winfo_children():
        widget.destroy()
    MenuScr()

2 个答案:

答案 0 :(得分:2)

time.sleep()在这里工作,因为它停止了程序的执行,你必须在...之后使用...而且在GUI编程中使用sleep也是一种不好的做法。 / p>

root.after(time_delay, function_to_run, args_of_fun_to_run)

所以在你的情况下它会像

一样
def destroy():
    #destroy here
    for widget in window.winfo_children():
        widget.destroy()

并在if语句之后 -

if __name__ == "__main__":
    StartUpScr()
    window.after(3000, destroy)
    MenuScr()

答案 1 :(得分:1)

所以我们定义了三个函数:firstScreensecondScreenchangeScreen。这个想法正在运行firstScreen,并在3秒后运行changeScreen,这会破坏当前的父窗口(master)并创建下一个全新的父窗口(master2)将致电secondScreen,它拥有全新的世界。这就是它将要发生的方式:

from tkinter import *
root = Tk()
import time

class App:
    def __init__(self, master):
        self.master = master
        self.master.geometry("500x500-500+50")

    def firstScreen(self):
        self.master.title("FIRST SCREEN")
        self.label1 = Label(self.master, width=50, height=20,
                            text="This is my FIRST screen", bg='red')
        self.label1.pack()
        self.master.after(3000, self.changeScreen)

    def secondScreen(self):
        self.label2 = Label(self.master, width=50, height=20,
                            text="This is my SECOND screen", bg='yellow')
        self.label2.pack()

    def changeScreen(self):
        self.master.destroy()
        self.master2 = Tk()
        self.master2.title('SECOND SCREEN')
        myapp = App(self.master2)
        myapp.secondScreen()

myapp = App(root)
myapp.firstScreen()

我希望它有所帮助!