使用Python实现带有警报框的Windows气泡提示/托 tray 提示通知

1 投票
1 回答
601 浏览
提问于 2025-04-18 01:10

我在Windows 7的电脑上使用Python 2.7。我的通知功能运行得很好。但是,当我加入一个警告框或对话框时,程序却忽略了这个警告框的代码,导致对话框没有弹出来。

我的通知代码是:

class WindowsBalloonTip:
    def __init__(self, title, msg):
        message_map = {
                win32con.WM_DESTROY: self.OnDestroy,
        }
        # Register the Window class.
        iconPathName= "D:\icon.ico"

        wc = WNDCLASS()
        hinst = wc.hInstance = GetModuleHandle(None)
        wc.lpszClassName = "PythonTaskbar"
        wc.lpfnWndProc = message_map # could also specify a wndproc.
        classAtom = RegisterClass(wc)
        # Create the Window.
        style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
        self.hwnd = CreateWindow( classAtom, "Taskbar", style, \
                0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, \
                0, 0, hinst, None)
        UpdateWindow(self.hwnd) 
        print iconPathName
        icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE
        try:
            hicon = LoadImage(hinst,iconPathName, win32con.IMAGE_ICON, 16, 16,icon_flags)
        except:
            hicon = LoadIcon(0, win32con.IDI_APPLICATION)
            logging.debug("Image adding fail")
        flags = NIF_ICON | NIF_MESSAGE | NIF_TIP
        nid = (self.hwnd, 0, flags, win32con.WM_USER+20, hicon, "title")
        Shell_NotifyIcon(NIM_ADD, nid)
        Shell_NotifyIcon(NIM_MODIFY, \
                         (self.hwnd, 0, NIF_INFO, win32con.WM_USER+20,\
                          hicon, "Balloon  tooltip",msg,200,title))
        # self.show_balloon(title, msg)
        global sleep
        time.sleep(sleep)
        DestroyWindow(self.hwnd)
        UnregisterClass(wc.lpszClassName, None)
    def OnDestroy(self, hwnd, msg, wparam, lparam):
        nid = (self.hwnd, 0)
        Shell_NotifyIcon(NIM_DELETE, nid)
        PostQuitMessage(0)

我的警告框代码是:

import win32api
a=0       
a=win32api.MessageBox(0, 'message', 'title',0)

首先,我是先使用通知,然后再使用对话框。在调试的时候,我发现问题出在UnregisterClass(wc.lpszClassName, hinst)这行代码上。我尝试过这段代码,但出现了一个错误,内容是:

classAtom = RegisterClass(wc)
pywintypes.error: (1410, 'RegisterClass', 'Class already exists.')

我的需求是在一个进程中从不同的函数调用通知代码,然后从其他函数调用对话框

1 个回答

1

我遇到了一个非常相似的问题:如何从Python线程刷新Windows气泡提示

看看这个:多个Windows气泡提示/托盘提示通知?

上面的解决办法让我可以关闭一个窗口并注销,但这只能在一个线程中进行。另一个线程不能处理同一个窗口。不确定这是否也适用于函数。

这只是一个评论,不是答案……但我现在还不到50。

撰写回答