首页 > 解决方案 > Python 3 通过代码关闭 tkinter 消息框

问题描述

我是 Python 新手,在第一个障碍上失败了。我有一个带有画布的消息框,其中加载了图像,通过被动红外传感器触发激活。

一切正常,但我希望消息框在 5 秒后消失。时间延迟不是问题,但试图让消息框走是另一回事,destroy()但没有。

了解有窗口级别即顶层。但想知道是否有人可以指出我正确的方向。

标签: python-3.xtkinter

解决方案


下面的小功能将完成这项工作。通过设置您可以选择的类型:信息、警告或错误消息框,默认为“信息”。您还可以设置超时时间,默认为 2.5 秒。

def showMessage(message, type='info', timeout=2500):
    import tkinter as tk
    from tkinter import messagebox as msgb

    root = tk.Tk()
    root.withdraw()
    try:
        root.after(timeout, root.destroy)
        if type == 'info':
            msgb.showinfo('Info', message, master=root)
        elif type == 'warning':
            msgb.showwarning('Warning', message, master=root)
        elif type == 'error':
            msgb.showerror('Error', message, master=root)
    except:
        pass

调用函数如下:对于消息类型“信息”和 2.5 秒的超时:

showMessage('Your message')

或者通过您自己的设置类型消息“错误”和超时 4 秒:

showMessage('Your message', type='error', timeout=4000)

推荐阅读