如何在循环中 运行 时关闭 tkinter 消息框?

How to close tkintermessagebox when it's running inside a loop?

我试图让 tkinter 消息框每隔 X 秒出现一次,我成功了,但是在按下取消按钮后消息框没有关闭,我该如何解决?

代码如下:

import Tkinter as tk
import tkMessageBox, time

root = tk.Tk()
root.withdraw()
tkMessageBox.showinfo('TITLE', 'FIRST MESSAGE')

def f():
    tkMessageBox.showinfo('TITLE', 'SECOND MESSAGE')
    tkMessageBox.showinfo('TITLE', 'THIRD MESSAGE')
    time.sleep(15)
while True:
    f()

sleep 调用冻结了应用程序。您可以使用 after 方法重复函数调用。

import Tkinter as tk
import tkMessageBox, time

root = tk.Tk()
root.withdraw()
tkMessageBox.showinfo('TITLE', 'FIRST MESSAGE')

def f():
    tkMessageBox.showinfo('TITLE', 'SECOND MESSAGE')
    tkMessageBox.showinfo('TITLE', 'THIRD MESSAGE')
    root.after(15000, f) # call f() after 15 seconds
    
f()

input('Press Enter to exit')   # or root.mainloop()

一般来说,您不应该在 tkinter 应用程序中调用 time.sleep(),因为这样做会干扰模块自己的 event-processing 循环。相反,您应该使用不带 callback 函数参数的通用小部件 after() 方法。

此外,您可以使您的代码更多 "data-driven" 以使其需要更少的代码修改。

下面是实现上述两个建议的示例
(并且将在 Python 2 和 3 中工作):

try:
    import Tkinter as tk
    import tkMessageBox
except ModuleNotFoundError:  # Python 3
    import tkinter as tk
    import tkinter.messagebox as tkMessageBox


DELAY = 3000  # Milliseconds - change as desired.
MESSAGE_BOXES = [
    ('Title1', 'First Message'),
    ('Title2', 'Second Message'),
    ('Title3', 'Third Message'),
]

root = tk.Tk()
root.withdraw()

def f():
    for msg_info in MESSAGE_BOXES:
        tkMessageBox.showinfo(*msg_info)
        root.after(DELAY)
    tkMessageBox.showinfo('Note', "That's all folks!")

f()