tkintermessagebox在循环中运行时如何关闭?

问题描述

我试图使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()

解决方法

sys调用将冻结应用程序。您可以使用sleep方法来重复函数调用。

after
,

通常来说,您不应在tkinter应用程序中调用time.sleep(),因为这样做会干扰模块自身的事件处理循环。相反,您应该使用没有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()