python-3.x - Python 3 通过代码关闭 tkinter 消息框
问题描述
我是 Python 新手,在第一个障碍上失败了。我有一个带有画布的消息框,其中加载了图像,通过被动红外传感器触发激活。
一切正常,但我希望消息框在 5 秒后消失。时间延迟不是问题,但试图让消息框走是另一回事,destroy()
但没有。
了解有窗口级别即顶层。但想知道是否有人可以指出我正确的方向。
解决方案
下面的小功能将完成这项工作。通过设置您可以选择的类型:信息、警告或错误消息框,默认为“信息”。您还可以设置超时时间,默认为 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)
推荐阅读
- replaykit - 将 ReplayKit 与 MacCatalyst 一起使用
- android - 我如何将多个数据添加到 firebase 实时数据库上的同一个令牌
- tcl - 无法理解 [lsort [::array names my_array *,dut_inst]] 的语法
- php - Woocommerce 以编程方式将购物车转换为订单
- node.js - req.cookies 在使用 nextjs 发出请求时被覆盖
- codenameone - 显示上传百分比的替代方法
- function - 在绘图的不同元素中使用函数“返回”的 2 个不同输出
- angular - 为角度“提供者”设置基本单元测试
- python - 有没有更好的方法为数据库中的表生成 python 类?
- python - 新的 venv 虚拟环境就像另一个已经存在的 env [Python]