Python消息弹框的使用


写在前面

python的tkinter中有消息弹框的实现,但这个方法有一个略微让人不爽的地方,需要在调用之前声明一个tk对象(不需要mainloop)并且调用withdraw隐藏,否则会有一个意料之外的窗口弹出,实际上是tkinter帮你创建了一个tk窗口。本文介绍一下tkinter消息弹框和Windows API弹框的使用。

tkinter

from tkinter import messagebox
from tkinter import Tk
root = Tk()
root.withdraw()
# 错误弹框
messagebox.showerror(title = 'Error',message = 'error message')
# 警告弹框
messagebox.showwarning(title = 'Warning',message = 'warning message')
# 信息弹框
messagebox.showinfo(title = 'Info',message = 'info message')

Windows API

import ctypes

MessageBoxW = ctypes.windll.user32.MessageBoxW
MessageBoxW.argtypes = [ctypes.c_int,ctypes.c_wchar_p,ctypes.c_wchar_p,ctypes.c_uint]

class MessageBox:
    @staticmethod
    def showwarning(title,message):
        MessageBoxW(ctypes.c_int(0),ctypes.c_wchar_p(message),
                    ctypes.c_wchar_p(title),ctypes.c_uint(0 | 0x30))

    @staticmethod
    def showerror(title,message):
        MessageBoxW(ctypes.c_int(0),ctypes.c_wchar_p(message),
                    ctypes.c_wchar_p(title),ctypes.c_uint(0 | 0x10))

    @staticmethod
    def showinfo(title,message):
        MessageBoxW(ctypes.c_int(0),ctypes.c_wchar_p(message),
                    ctypes.c_wchar_p(title),ctypes.c_uint(0 | 0x40))

# 错误弹框
MessageBox.showerror(title = 'Error',message = 'error message')
# 警告弹框
MessageBox.showwarning(title = 'Warning',message = 'warning message')
# 信息弹框
MessageBox.showinfo(title = 'Info',message = 'info message')