如何自动销毁堆栈中的帧切换时间并返回到 tkinter 中的上一帧

how to automatically destroy the frameover time in the stack and go back to previous frame in tkinter

我有多个通过按钮调用的框架,我使用的方法是堆叠方法。 现在我遇到了一段时间后自动销毁框架并返回到上一帧的问题。 例如 在 Main.py

import tkinter as tk                # python 3
from pageOne import PageOne
from tkinter import font  as tkfont # python 3
class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne, PageTwo):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame
            frame.grid(row=0, column=0, sticky="nsew")
        self.show_frame("StartPage")

    def show_frame(self, page_name):
            '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()

class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is the start page", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(self, text="Go to Page One",
                                command=lambda: controller.show_frame("PageOne"))
        button2 = tk.Button(self, text="Go to Page Two",
                                command=lambda: controller.show_frame("PageTwo"))
        button1.pack()
        button2.pack()

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

在pageOne.py

from tkinter import *
class PageOne(Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                               command=lambda: controller.show_frame("StartPage"))
        button.pack()

现在我想在一段时间后自动关闭 pageOne 并返回到 StartPage。

我试过了

def show_frame(self, page_name):
    if page_name == PageOne:
        page_name.after(5000,PageOne.destroy())
        frame = self.frames[StartPage]
        frame.tkraise()
    frame = self.frames[page_name]
    frame.tkraise()

但是没用

如果您只想自动切换到不同的页面,您以后可以使用after调用show_frame。没有理由销毁页面。

def show_frame(self, page_name):
    if page_name == "PageOne":
        self.after(5000, self.show_frame, "StartPage")
    frame = self.frames[page_name]
    frame.tkraise()