📜  Python| Tkinter 中的 after 方法

📅  最后修改于: 2022-05-13 01:54:30.209000             🧑  作者: Mango

Python| Tkinter 中的 after 方法

Tkinter 提供多种内置功能开发交互式和特色 GUI(图形用户界面)。 after()函数也是一个通用函数,可以直接在根上使用,也可以与其他小部件一起使用。

after(parent, ms, function = None, *args)

代码#1:

Python3
# importing only those functions which
# are needed
from tkinter import Tk, mainloop, TOP
from tkinter.ttk import Button
 
# time function used to calculate time
from time import time
 
# creating tkinter window
root = Tk()
 
button = Button(root, text = 'Geeks')
button.pack(side = TOP, pady = 5)
 
print('Running...')
# Calculating starting time
start = time()
 
# in after method 5000 milliseconds
# is passed i.e after 5 seconds
# main window i.e root window will
# get destroyed
root.after(5000, root.destroy)
 
mainloop()
 
# calculating end time
end = time()
print('Destroyed after % d seconds' % (end-start))


Python3
# importing only those functions which
# are needed
from tkinter import Tk, mainloop, TOP
from tkinter.ttk import Button
from tkinter.messagebox import _show
 
# creating tkinter window
root = Tk()
root.geometry('200x100 + 300 + 250')
 
button = Button(root, text = 'Geeks')
button.pack(side = TOP, pady = 5)
 
# in after method 5000 milliseconds
# is passed i.e after 5 seconds
# a message will be prompted
root.after(5000, lambda : _show('Title', 'Prompting after 5 seconds'))
 
# Destroying root window after 6.7 seconds
root.after(6700, root.destroy)
 
mainloop()


输出:

当您运行该程序时,它会显示一个带有 Button 的 Tkinter 窗口,但 5 秒后该窗口被破坏。
代码 #2:在特定时间后提示消息(在我们的程序中 5 秒后)。

Python3

# importing only those functions which
# are needed
from tkinter import Tk, mainloop, TOP
from tkinter.ttk import Button
from tkinter.messagebox import _show
 
# creating tkinter window
root = Tk()
root.geometry('200x100 + 300 + 250')
 
button = Button(root, text = 'Geeks')
button.pack(side = TOP, pady = 5)
 
# in after method 5000 milliseconds
# is passed i.e after 5 seconds
# a message will be prompted
root.after(5000, lambda : _show('Title', 'Prompting after 5 seconds'))
 
# Destroying root window after 6.7 seconds
root.after(6700, root.destroy)
 
mainloop()

输出:
在下面的输出中,将在 5 秒后提示一个消息框,您甚至可以通过传递函数名称在一段时间后调用任何函数。