tkinter延迟后显示帧

时间:2016-12-03 19:43:03

标签: python tkinter

我想用3页制作一个GUI。起始页面有标题和开始按钮。按下开始按钮后,将显示PageOne,5秒后,将显示PageTwo。 但是,现在它以不同的方式工作:单击按钮时,等待5秒,并保持起始页面。然后展示了PageOne和PageTwo,我只能看到PageTwo 有人会告诉我如何解决这个问题?非常感谢。

import tkinter as tk
import time

class MyApp(tk.Tk):
    def __init__(self, height, width):
        tk.Tk.__init__(self)
        self.geometry('{}x{}'.format(height, width))
        self.resizable(width=False, height=False)
        self.container = tk.Frame(self)
        self.container.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        self.container.grid_rowconfigure(0, weight=1)
        self.container.grid_columnconfigure(0, weight=1)  

        self.frames = {}
        for f in [StartPage, PageOne, PageTwo]:
            self.frames[f] = f(self.container, self)
            self.frames[f].config(height=height)
            self.frames[f].config(width=width)
            self.frames[f].grid(row=0, column=0, sticky="nsew")
        self.show_frame(StartPage)

    def show_frame(self, page):
        self.frames[page].tkraise()



class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.parent = parent
        self.controller = controller
        self.create_widgets()

    def create_widgets(self): 
        self.instruction = tk.Label(self, text='My Title')
        self.instruction.config(font=("Courier", 20))
        self.instruction.place(relx=0.5, rely=0.3, anchor=tk.CENTER)
        self.button = tk.Button(self, text = 'START', command=self.click_start)
        self.button.place(relx=0.5, rely=0.5, anchor=tk.CENTER)

    def click_start(self):
        # show PageOne
        self.controller.show_frame(PageOne)
        # wait for 5 seconds
        time.sleep(5)
        # show PageTwo
        self.controller.show_frame(PageTwo)

class PageOne(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.parent = parent
        self.controller = controller
        self.create_widgets()

    def create_widgets(self): 
        self.label = tk.Label(self,text='PageOne')
        self.label.config(font=("Courier", 20))
        self.label.place(relx=0.4, rely=0.4, anchor=tk.CENTER)

class PageTwo(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.parent = parent
        self.controller = controller
        self.create_widgets()

    def create_widgets(self):
        self.label = tk.Label(self, text='PageTwo')
        self.label.config(font=("Courier", 30))
        self.label.place(relx=0.5, rely=0.5, anchor=tk.CENTER)

if __name__ == '__main__':        
    root = MyApp(height=500, width=500)
    root.mainloop()

1 个答案:

答案 0 :(得分:1)

您可以使用after窗口小部件方法来安排未来事件。第一个参数是一个毫秒,下一个参数是对函数的引用,任何其他参数将传递给函数。

def click_start(self):
    self.controller.show_frame(PageOne)
    self.controller.after(5000, self.controller.show_frame, PageTwo)