[Python3]关于桌面托盘和气泡QwQ

最近写个工程的时候踩的大坑QAQ。。。

前言

看了一下上次的更新时间,2018-11-06。。。

这个Blog也算是荒了一阵子了(期末考啊我也很无奈啊。。。

然后在我的好友mnihyc骚扰劝说下,打算继续更新Blog。(虽然他的Blog这段时间内崩了一回,数据都没了

所以我也没啥好写的,就水一篇博客吧,嘻嘻。

正文

关于这个Python的桌面托盘上的事,某度上基本没啥资料。。。

其实我主要是因为Win10的气泡提醒看起来还不错,就懒得自己写个窗口了。

然后我就一直找气泡提醒。。。。。。结果找到了下面两个(可用的

1. 这是socrates大佬的,2012年更新的(还tm要依赖这个模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
#!/usr/bin/env python
# -*- coding: utf-8 -*-

#gtkPopupNotify.py
#
# Copyright 2009 Daniel Woodhouse
# modified by NickCis 2010 http://github.com/NickCis/gtkPopupNotify
# Modifications:
# Added: * Corner support (notifications can be displayed in all corners
# * Use of gtk Stock items or pixbuf to render images in notifications
# * Posibility of use fixed height
# * Posibility of use image as background
# * Not displaying over Windows taskbar(taken from emesene gpl v3)
# * y separation.
# * font description options
# * Callbacks For left, middle and right click
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU Lesser General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU Lesser General Public License for more details.
#
#You should have received a copy of the GNU Lesser General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.


import os
import gtk
import pango
import gobject

# This code is used only on Windows to get the location on the taskbar
# Taken from emesene Notifications (Gpl v3)
taskbarOffsety = 0
taskbarOffsetx = 0
if os.name == "nt":
import ctypes
from ctypes.wintypes import RECT, DWORD
user = ctypes.windll.user32
MONITORINFOF_PRIMARY = 1
HMONITOR = 1

class MONITORINFO(ctypes.Structure):
_fields_ = [
('cbSize', DWORD),
('rcMonitor', RECT),
('rcWork', RECT),
('dwFlags', DWORD)
]

taskbarSide = "bottom"
taskbarOffset = 30
info = MONITORINFO()
info.cbSize = ctypes.sizeof(info)
info.dwFlags = MONITORINFOF_PRIMARY
user.GetMonitorInfoW(HMONITOR, ctypes.byref(info))
if info.rcMonitor.bottom != info.rcWork.bottom:
taskbarOffsety = info.rcMonitor.bottom - info.rcWork.bottom
if info.rcMonitor.top != info.rcWork.top:
taskbarSide = "top"
taskbarOffsety = info.rcWork.top - info.rcMonitor.top
if info.rcMonitor.left != info.rcWork.left:
taskbarSide = "left"
taskbarOffsetx = info.rcWork.left - info.rcMonitor.left
if info.rcMonitor.right != info.rcWork.right:
taskbarSide = "right"
taskbarOffsetx = info.rcMonitor.right - info.rcWork.right

class NotificationStack:

def __init__(self, size_x=300, size_y=-1, timeout=5, corner=(False, False), sep_y=0):
"""
Create a new notification stack. The recommended way to create Popup instances.
Parameters:
`size_x` : The desired width of the notifications.
`size_y` : The desired minimum height of the notifications. If it isn't set,
or setted to None, the size will automatically adjust
`timeout` : Popup instance will disappear after this timeout if there
is no human intervention. This can be overridden temporarily by passing
a new timout to the new_popup method.
`coner` : 2 Value tuple: (true if left, True if top)
`sep_y` : y distance to separate notifications from each other
"""
self.size_x = size_x
self.size_y = -1
if (size_y == None):
pass
else:
size_y
self.timeout = timeout
self.corner = corner
self.sep_y = sep_y
"""
Other parameters:
These will take effect for every popup created after the change.

`edge_offset_y` : distance from the bottom of the screen and
the bottom of the stack.
`edge_offset_x` : distance from the right edge of the screen and
the side of the stack.
`max_popups` : The maximum number of popups to be shown on the screen
at one time.
`bg_color` : if None default is used (usually grey). set with a gtk.gdk.Color.
`bg_pixmap` : Pixmap to use as background of notification. You can set a gtk.gdk.Pixmap
or a path to a image. If none, the color background will be displayed.
`bg_mask` : If a gtk.gdk.pixmap is specified under bg_pixmap, the mask of the pixmap has to be setted here.
`fg_color` : if None default is used (usually black). set with a gtk.gdk.Color.
`show_timeout` : if True, a countdown till destruction will be displayed.
`close_but` : if True, the close button will be displayed.
`fontdesc` : a 3 value Tuple containing the pango.FontDescriptions of the Header, message and counter
(in that order). If a string is suplyed, it will be used for the 3 the same FontDescription.
http://doc.stoq.com.br/devel/pygtk/class-pangofontdescription.html
"""
self.edge_offset_x = 0
self.edge_offset_y = 0
self.max_popups = 5
self.fg_color = None
self.bg_color = None
self.bg_pixmap = None
self.bg_mask = None
self.show_timeout = False
self.close_but = True
self.fontdesc = ("Sans Bold 14", "Sans 12", "Sans 10")

self._notify_stack = []
self._offset = 0


def new_popup(self, title, message, image=None, leftCb=None, middleCb=None, rightCb=None):
"""Create a new Popup instance."""
if len(self._notify_stack) == self.max_popups:
self._notify_stack[0].hide_notification()
self._notify_stack.append(Popup(self, title, message, image, leftCb, middleCb, rightCb))
self._offset += self._notify_stack[-1].y

def destroy_popup_cb(self, popup):
self._notify_stack.remove(popup)
#move popups down if required
offset = 0
for note in self._notify_stack:
offset = note.reposition(offset, self)
self._offset = offset




class Popup(gtk.Window):
def __init__(self, stack, title, message, image, leftCb, middleCb, rightCb):
gtk.Window.__init__(self, type=gtk.WINDOW_POPUP)

self.leftclickCB = leftCb
self.middleclickCB = middleCb
self.rightclickCB = rightCb

self.set_size_request(stack.size_x, stack.size_y)
self.set_decorated(False)
self.set_deletable(False)
self.set_property("skip-pager-hint", True)
self.set_property("skip-taskbar-hint", True)
self.connect("enter-notify-event", self.on_hover, True)
self.connect("leave-notify-event", self.on_hover, False)
self.set_opacity(0.2)
self.destroy_cb = stack.destroy_popup_cb

if type(stack.fontdesc) == tuple or type(stack.fontdesc) == list:
fontH, fontM, fontC = stack.fontdesc
else:
fontH = fontM = fontC = stack.fontdesc

main_box = gtk.VBox()
header_box = gtk.HBox()
self.header = gtk.Label()
self.header.set_markup("<b>%s</b>" % title)
self.header.set_padding(3, 3)
self.header.set_alignment(0, 0)
try:
self.header.modify_font(pango.FontDescription(fontH))
except Exception, e:
print e
header_box.pack_start(self.header, True, True, 5)
if stack.close_but:
close_button = gtk.Image()

close_button.set_from_stock(gtk.STOCK_CANCEL, gtk.ICON_SIZE_BUTTON)
close_button.set_padding(3, 3)
close_window = gtk.EventBox()
close_window.set_visible_window(False)
close_window.connect("button-press-event", self.hide_notification)
close_window.add(close_button)
header_box.pack_end(close_window, False, False)
main_box.pack_start(header_box)

body_box = gtk.HBox()
if image is not None:
self.image = gtk.Image()
self.image.set_size_request(70, 70)
self.image.set_alignment(0, 0)
if image in gtk.stock_list_ids():
self.image.set_from_stock(image, gtk.ICON_SIZE_DIALOG)
elif type(image) == gtk.gdk.Pixbuf:
self.image.set_from_pixbuf(image)
else:
self.image.set_from_file(image)
body_box.pack_start(self.image, False, False, 5)
self.message = gtk.Label()
self.message.set_property("wrap", True)
self.message.set_size_request(stack.size_x - 90, -1)
self.message.set_alignment(0, 0)
self.message.set_padding(5, 10)
self.message.set_markup(message)
try:
self.message.modify_font(pango.FontDescription(fontM))
except Exception, e:
print e
self.counter = gtk.Label()
self.counter.set_alignment(1, 1)
self.counter.set_padding(3, 3)
try:
self.counter.modify_font(pango.FontDescription(fontC))
except Exception, e:
print e
self.timeout = stack.timeout

body_box.pack_start(self.message, True, False, 5)
body_box.pack_end(self.counter, False, False, 5)
main_box.pack_start(body_box)
eventbox = gtk.EventBox()
eventbox.set_property('visible-window', False)
eventbox.set_events(gtk.gdk.BUTTON_PRESS_MASK)
eventbox.connect("button_press_event", self.onClick)
eventbox.add(main_box)
self.add(eventbox)
if stack.bg_pixmap is not None:
if not type(stack.bg_pixmap) == gtk.gdk.Pixmap:
stack.bg_pixmap, stack.bg_mask = gtk.gdk.pixbuf_new_from_file(stack.bg_pixmap).render_pixmap_and_mask()
self.set_app_paintable(True)
self.connect_after("realize", self.callbackrealize, stack.bg_pixmap, stack.bg_mask)
elif stack.bg_color is not None:
self.modify_bg(gtk.STATE_NORMAL, stack.bg_color)
if stack.fg_color is not None:
self.message.modify_fg(gtk.STATE_NORMAL, stack.fg_color)
self.header.modify_fg(gtk.STATE_NORMAL, stack.fg_color)
self.counter.modify_fg(gtk.STATE_NORMAL, stack.fg_color)
self.show_timeout = stack.show_timeout
self.hover = False
self.show_all()
self.x, self.y = self.size_request()
#Not displaying over windows bar
if os.name == 'nt':
if stack.corner[0] and taskbarSide == "left":
stack.edge_offset_x += taskbarOffsetx
elif not stack.corner[0] and taskbarSide == 'right':
stack.edge_offset_x += taskbarOffsetx
if stack.corner[1] and taskbarSide == "top":
stack.edge_offset_x += taskbarOffsety
elif not stack.corner[1] and taskbarSide == 'bottom':
stack.edge_offset_x += taskbarOffsety

if stack.corner[0]:
posx = stack.edge_offset_x
else:
posx = gtk.gdk.screen_width() - self.x - stack.edge_offset_x
sep_y = 0
if (stack._offset == 0):
pass
else:
stack.sep_y
self.y += sep_y
if stack.corner[1]:
posy = stack._offset + stack.edge_offset_y + sep_y
else:
posy = gtk.gdk.screen_height()- self.y - stack._offset - stack.edge_offset_y
self.move(posx, posy)
self.fade_in_timer = gobject.timeout_add(100, self.fade_in)



def reposition(self, offset, stack):
"""Move the notification window down, when an older notification is removed"""
if stack.corner[0]:
posx = stack.edge_offset_x
else:
posx = gtk.gdk.screen_width() - self.x - stack.edge_offset_x
if stack.corner[1]:
posy = offset + stack.edge_offset_y
new_offset = self.y + offset
else:
new_offset = self.y + offset
posy = gtk.gdk.screen_height() - new_offset - stack.edge_offset_y + stack.sep_y
self.move(posx, posy)
return new_offset


def fade_in(self):
opacity = self.get_opacity()
opacity += 0.15
if opacity >= 1:
self.wait_timer = gobject.timeout_add(1000, self.wait)
return False
self.set_opacity(opacity)
return True

def wait(self):
if not self.hover:
self.timeout -= 1
if self.show_timeout:
self.counter.set_markup(str("<b>%s</b>" % self.timeout))
if self.timeout == 0:
self.fade_out_timer = gobject.timeout_add(100, self.fade_out)
return False
return True


def fade_out(self):
opacity = self.get_opacity()
opacity -= 0.10
if opacity <= 0:
self.in_progress = False
self.hide_notification()
return False
self.set_opacity(opacity)
return True

def on_hover(self, window, event, hover):
"""Starts/Stops the notification timer on a mouse in/out event"""
self.hover = hover


def hide_notification(self, *args):
"""Destroys the notification and tells the stack to move the
remaining notification windows"""
for timer in ("fade_in_timer", "fade_out_timer", "wait_timer"):
if hasattr(self, timer):
gobject.source_remove(getattr(self, timer))
self.destroy()
self.destroy_cb(self)

def callbackrealize(self, widget, pixmap, mask=False):
#width, height = pixmap.get_size()
#self.resize(width, height)
if mask is not False:
self.shape_combine_mask(mask, 0, 0)
self.window.set_back_pixmap(pixmap, False)
return True

def onClick(self, widget, event):
if event.button == 1 and self.leftclickCB != None:
self.leftclickCB()
self.hide_notification()
if event.button == 2 and self.middleclickCB != None:
self.middleclickCB()
self.hide_notification()
if event.button == 3 and self.rightclickCB != None:
self.rightclickCB()
self.hide_notification()

if __name__ == "__main__":
#example usage

def notify_factory():
color = ("green", "blue")
image = "logo1_64.png"
notifier.bg_color = gtk.gdk.Color(color[0])
notifier.fg_color = gtk.gdk.Color(color[1])
notifier.show_timeout = True
notifier.edge_offset_x = 20
notifier.edge_offset_y = 30
notifier.new_popup("Windows上的泡泡提示", "NND,比Linux下复杂多了,效果还不怎么样", image=image)
return True

def gtk_main_quit():
print "quitting"
gtk.main_quit()

notifier = NotificationStack(timeout=1)
gobject.timeout_add(4000, notify_factory)
gobject.timeout_add(8000, gtk_main_quit)
gtk.main()

这个我不知道能不能用(反正这个不是Python3的

不过好像用的也不是Win10下原汁原味的提示。。。

2.emmm我不知道扔哪里去了

至少这个可以用,是利用Python3调用winAPI

然后瞎搞搞。。。。(反正我是觉得太麻烦了啊

解决方案

最后,我想到了我的wxPython是不是有这样的功能

然后百度了一下

找到了这个j*玩意,居然是wxPython+winAPI的???

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import wx
import win32gui
import win32con
import time
from winxpgui import *


class SparkTaskBarIcon(wx.TaskBarIcon):
TBMENU_RESTORE = wx.NewId()
TBMENU_CLOSE = wx.NewId()
TBMENU_CHANGE = wx.NewId()
TBMENU_REMOVE = wx.NewId()

def __init__(self, frame,picon,icon):
wx.TaskBarIcon.__init__(self)
self.frame = frame
# Set the image
#icon = self.MakeIcon(images.WXPdemo.GetImage())
wc = win32gui.WNDCLASS()
hinst = wc.hInstance = win32gui.GetModuleHandle(None)
icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE
hicon = LoadImage(hinst, icon, win32con.IMAGE_ICON, 0, 0, icon_flags)

self.SetIcon(picon, "Spark")
self.imgidx = 1

# bind some events
self.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.OnTaskBarActivate)
self.Bind(wx.EVT_MENU, self.OnTaskBarActivate, id=self.TBMENU_RESTORE)
self.Bind(wx.EVT_MENU, self.OnTaskBarClose, id=self.TBMENU_CLOSE)
#self.Bind(wx.EVT_MENU, self.OnTaskBarChange, id=self.TBMENU_CHANGE)
self.Bind(wx.EVT_MENU, self.OnTaskBarRemove, id=self.TBMENU_REMOVE)

#气泡提示注册win的窗口消息
wc.lpszClassName = "Spark"
wc.lpfnWndProc = {win32con.WM_DESTROY: self.OnDestroy,}
classAtom = win32gui.RegisterClass(wc)
style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
self.hwnd = win32gui.CreateWindow( classAtom, "Spark", style,
0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT,
0, 0, hinst, None)
#hicon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION)
nid = (self.hwnd, 0, win32gui.NIF_ICON, win32con.WM_USER+20, hicon, "Spark")
win32gui.Shell_NotifyIcon(win32gui.NIM_ADD, nid)

def OnDestroy(self, hwnd, msg, wparam, lparam):
nid = (self.hwnd, 0)
win32gui.Shell_NotifyIcon(win32gui.NIM_DELETE, nid)
win32gui.PostQuitMessage(0) # Terminate the app.

def showMsg(self, title, msg):
# 原作者使用Shell_NotifyIconA方法代替包装后的Shell_NotifyIcon方法
# 据称是不能win32gui structure, 我稀里糊涂搞出来了.
# 具体对比原代码.
nid = (self.hwnd, # 句柄
0, # 托盘图标ID
win32gui.NIF_INFO, # 标识
0, # 回调消息ID
0, # 托盘图标句柄
"Spark Message", # 图标字符串
msg, # 气球提示字符串
5, # 提示的显示时间
title, # 提示标题
win32gui.NIIF_INFO # 提示用到的图标
)
win32gui.Shell_NotifyIcon(win32gui.NIM_MODIFY, nid)
def CreatePopupMenu(self):
"""
This method is called by the base class when it needs to popup
the menu for the default EVT_RIGHT_DOWN event. Just create
the menu how you want it and return it from this function,
the base class takes care of the rest.
"""
menu = wx.Menu()
menu.Append(self.TBMENU_RESTORE, "Restore spark")
menu.Append(self.TBMENU_CLOSE, "Close spark")
menu.AppendSeparator()
#menu.Append(self.TBMENU_CHANGE, "Change the TB Icon")
menu.Append(self.TBMENU_REMOVE, "Remove Spark")
return menu

#def MakeIcon(self, img):
#"""
#The various platforms have different requirements for the
#icon size...
#"""
#if "wxMSW" in wx.PlatformInfo:
#img = img.Scale(16, 16)
#elif "wxGTK" in wx.PlatformInfo:
#img = img.Scale(22, 22)
## wxMac can be any size upto 128x128, so leave the source img alone....
#icon = wx.IconFromBitmap(img.ConvertToBitmap() )
#return icon

def OnTaskBarActivate(self, evt):
if self.frame.IsIconized():
self.frame.Iconize(False)
if not self.frame.IsShown():
self.frame.Show(True)
self.frame.Raise()

def OnTaskBarClose(self, evt):
wx.CallAfter(self.frame.OnClose)

#def OnTaskBarChange(self, evt):
#names = [ "WXPdemo", "Mondrian", "Pencil", "Carrot" ]
#name = names[self.imgidx]

#eImg = getattr(images, name)
#self.imgidx += 1
#if self.imgidx >= len(names):
#self.imgidx = 0

#icon = self.MakeIcon(eImg.Image)
#self.SetIcon(icon, "This is a new icon: " + name)

def OnTaskBarRemove(self, evt):
self.RemoveIcon()

不过至少是实现了这一功能

但是英明的我怎么会满足于此呢?(我tm写个气泡提示就要这么长真的难受。。。。

于是我开开心心地Google了一下,居然还是没有????

但是,我在一篇用winAPI解决的Blog里看到了这个

有一个小需求希望在wx下建立的托盘区图标上显示气球消息,很尴尬的是wx.TaskBarIcon不像wx.Window等有GetHandle方法,无法直接获得句柄.解决的办法1.自己重写TaskBarIcon… 2.直接遍历找到句柄(更通用麻烦些).据说wxpython在2.9后会加一个wx.NotificationMessage方法,但是2.9….哪年月有动静呢?

哇这个wx.NotificationMessage是个什么东西

然后看了看wxPython官网,都TM4.0.4了,你这什么LJ版本。

于是我终于在官方文档里找到了这个东西。。。

(居然还是wx.adv模块里的。。。

调用方法简单来写就是

1
wx.adv.NotificationMessage(title,message).Show()

至少用一句话代替了上面那坨100+行的winAPI

具体方法的话请Click

后记

不过这个东西还是不能完美的实现这个功能,他在通知的时候就会在托盘里加一个Python的图标。。。

这个东西我也没啥好办法,将就用着吧,如果你有什么方法可以解决(别TM说winAPI),请email我!

(这个东西耗了我1个小时,我……QAQ