我目前正在开发一个 GUI,我希望我的 GUI 在最后一帧上停留 5 秒,然后从最后一帧返回到第一帧而不进行任何交互。
如果我使用 after
小部件方法,则计时器从应用程序的开头开始。
如果我将它放在一个方法中,并且调用该方法,则会发生相同的行为。另一方面,如果我通过按钮调用该函数,它就会按预期工作。
Controller
# The code for changing pages was derived from:
http://stackoverflow.com/questions/7546050/switch-between-two-frames-in-tkinter
# License: http://creativecommons.org/licenses/by-sa/3.0/
import tkinter as tk
LARGE_FONT= ("Verdana", 12)
class SeaofBTCapp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
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):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
StartPage
类
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
label = tk.Label(self, text="Start Page", font=LARGE_FONT)
label.pack(pady=10,padx=10)
button = tk.Button(self, text="Visit Page 1",
command=lambda: controller.show_frame(PageOne))
button.pack()
button2 = tk.Button(self, text="Visit Page 2",
command=lambda: controller.show_frame(PageTwo))
button2.pack()
PageOne
类
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Page One!!!", font=LARGE_FONT)
label.pack(pady=10,padx=10)
button1 = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.pack()
button2 = tk.Button(self, text="Page Two",
command=lambda: controller.show_frame(PageTwo))
button2.pack()
PageTwo
类
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Page Two!!!", font=LARGE_FONT)
label.pack(pady=10,padx=10)
button1 = tk.Button(self, text="Back to Home",
command=lambda:self.start_reset())
button1.pack()
button2 = tk.Button(self, text="Page One",
command=lambda: controller.show_frame(PageOne))
button2.pack()
# self.after(5000,self.controller.show_frame(StartPage)) works only
# once and the time starts from the start of the GUI and after 5000ms it takes
# the gui to the start page no matter what
def start_reset(self):
self.after(5000,self.controller.show_frame(StartPage))
app = SeaofBTCapp()
app.mainloop()
最佳答案
有几个地方可以调用 after
方法。
对我来说,如果将其放置在 Controller 类中更有意义,因为它旨在管理组件。
实现此目的的一个直接方法是完成 SeaofBTCapp.show_frame
方法:
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
if cont == PageTwo:
self.after(5000, self.show_frame, StartPage)
调用 show_frame
方法时,会计划以 StartPage
作为参数调用 show_frame
。
关于python - 如何使用时间而不使用按钮命令更改 tkinter 中的帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46048610/