jithurjacob / windows-10-toast-notifications Goto Github PK
View Code? Open in Web Editor NEWPython library to display Windows 10 Toast Notifications
License: MIT License
Python library to display Windows 10 Toast Notifications
License: MIT License
I'm sort of missing the fact that this even works on Windows 7 in the README....
that's not a total obvious fact...
The class can not be instantiated for any other instance.
It is not possible to have a second notifier instance running with different purpose.
from win10toast import ToastNotifier as T
t1=T() #instance 1
t2=T() #instance 2
Raises class already exists error.
Hello!
I am getting an error when trying to import this into my project:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
from win10toast import ToastNotifier
File "C:\Users\Luka\AppData\Roaming\Python\Python38\site-packages\win10toast\__init__.py", line 19, in <module>
from win32api import GetModuleHandle
ModuleNotFoundError: No module named 'win32api'
It seems win32api is missing. So I go ahead and install it with this command: python -m pip install win32api --user
. I have to use --user
as I am not an admin on my PC. The following error occurs...
ERROR: Could not find a version that satisfies the requirement win32api (from versions: none)
ERROR: No matching distribution found for win32api
So I try: python -m pip install pypiwin32 --user
, as this is listed in requirements section. I already have it.
I am using Python 3.8.0 and IDLE, on a Windows 10 PC.
So what am I doing wrong?
Thanks!
When i am displaying an icon in the notification it appears to be quite small no matter what size/resolution icon file i have. Is there a way to make the icon appear bigger in the notification?
https://github.com/Infinidat/infi.systray is a great helper to allow system tray options for your Python app.
Would you be willing to support spawning notifications from an existing tray instance to avoid two separate icons showing up?
When you click the notification is it possible to select the application that triggered the notification?
It seems like the program automatically exit after toast being run. Is there any way to sustain the application?
In your readme.md please change your example to:
from win10toast import ToastNotifier
import time
toaster = ToastNotifier()
toaster.show_toast("Hello World!!!",
"Python is 10 seconds awsm!",
icon_path="custom.ico",
duration=10)
toaster.show_toast("Example two",
"This notification is in it's own thread!",
icon_path=None,
duration=5,
threaded=True)
# Wait for threaded notification to finish
while toaster.notification_active(): time.sleep(0.1)
It doesn't matter much, but would be easier to copy-paste :)
Since you updated win10toast in the pip repository, installation does not work anymore for me. It looks like the requirements.txt file can not be found. For reference, this is the error:
PS C:\Python 361\VENVs\Test\Scripts> .\pip.exe install win10toast --no-cache-dir
Collecting win10toast
Downloading win10toast-0.8.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "C:\Python 361\VENVs\Test\lib\site-packages\pip-9.0.1-py3.6.egg\pip\download.py", line 421, in get_file_content
with open(url, 'rb') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\flori\\AppData\\Local\\Temp\\pip-build-u758glcl\\win10toast\\requirements.txt'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\flori\AppData\Local\Temp\pip-build-u758glcl\win10toast\setup.py", line 18, in <module>
parse_requirements(from_here("requirements.txt"), session="")
File "C:\Python 361\VENVs\Test\lib\site-packages\pip-9.0.1-py3.6.egg\pip\req\req_file.py", line 84, in parse_requirements
filename, comes_from=comes_from, session=session
File "C:\Python 361\VENVs\Test\lib\site-packages\pip-9.0.1-py3.6.egg\pip\download.py", line 425, in get_file_content
'Could not open requirements file: %s' % str(exc)
pip.exceptions.InstallationError: Could not open requirements file: [Errno 2] No such file or directory: 'C:\\Users\\flori\\AppData\\Local\\Temp\\pip-build-u758glcl\\win10toast\\requirements.txt'
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\flori\AppData\Local\Temp\pip-build-u758glcl\win10toast\
When I try to pip install win10toast
, I get the error message
Collecting pywin32 (from win10toast)
Could not find a version that satisfies the requirement pywin32 (from win10toast) (from versions: )
No matching distribution found for pywin32 (from win10toast)
I guess it's becuase the version in PyPI has not been updated yet, to install pypiwin32, instead of pywin32.
Would be much better to have this class either in __init__.py
or its own file
This is especially weird because __name__
is either __main__
or win10toast.__main__
how can i set size for the notifications ?? such as with andlength ?? thanks...
Hi,
I've been using this library for a long time and never had any problems. Recently I let Windows update with it's latest update, and right after that I stopped getting notification from my program. I tested this by creating a simple python file with only the sample code of this library and again the notification didn't popup. I noticed whenever the notification was supposed to popup it will only show an icon in the system tray and not show the notification.
I suspect this has to do with Windows' feature of "Focus Assist" that I only noticed recently. I also noticed that there is a white-list of programs in the "Notifications & Actions" section of Settings, where you can enable or disable notifications from certain programs and sources, which I'm not sure was there before.
Would really appreciate a feedback on this as this library is very crucial for my application.
Thank you.
'ToastNotifier' object has no attribute 'classAtom'
Python WNDPROC handler failed
Traceback (most recent call last):
File "C:\Users\vanjaneya\AppData\Local\Programs\Python\Python37-32\lib\site-packages\win10toast_init_.py", line 153, in on_destroy
Shell_NotifyIcon(NIM_DELETE, nid)
pywintypes.error: (-2147467259, 'Shell_NotifyIcon', 'Unspecified error')
My code is similar this
import sys
import json
import time
from functools import partial
from win10toast import ToastNotifier
from multiprocessing import Pool
def callNot(index):
try:
print("index",index)
toaster = ToastNotifier()
toaster.show_toast(index + " creation SUCCEEDED", "File containing informations is available.")
except:
print('error')
if name == 'main':
pool = Pool(int(50))
func = partial(callNot)
result = pool.map(func,str(1234567891011133333333333333333333333311111111111))
pool.close()
pool.join()
Looking primarily to get the multi-threading code pushed to pypi for a project that relied upon pip for package installation.
Hello,
I have installed the "win10toast" module using follwing command:
pip install win10toast
If I try to import the module using:
from win10toast import ToastNotifier
I keep getting this error:
ModuleNotFoundError: No module named 'win10toast'
Should be stripped of their surrounding if statement, and moved to __main__.py
.
That way, the example can be run with python -m win10toast
No matter how much duration value set, the toast always destructs after some specified time (around 3 seconds). Please take a look into this.
Or am I doing it wrong?
is possible that the notification will remain in the Notification Center ?
Right now I am trying to display five lines of a notification but the system is only able to display first 4 lines. Is it the limitation or am i missing something.
I would like to be able to dismiss any notifications I have created.
I think this could be achieved with a function that takes the handle of the notification to be cancelled, and with show_toast returning the handle of the new notification.
So while building the project, I have encountered an issue with pip module while in setup.py
In pip versions greater than 10 parse_requirements is in pip._internal.req instead of pip.req. Here is a snippet on how I fixed it.
diff --git a/setup.py b/setup.py
index 8ead33e..a1ef1ad 100644
--- a/setup.py
+++ b/setup.py
@@ -2,7 +2,10 @@
from operator import attrgetter
from os import path
-from pip.req import parse_requirements
+try: # for pip >= 10
+ from pip._internal.req import parse_requirements
+except ImportError: # for pip <= 9.0.3
+ from pip.req import parse_requirements
from setuptools import setup
def read(fname):
setuptools
is required for pkg_resources
to be available
I was in the process of adding this functionality in order to make a pull request, but sadly there were some limitations, and I don't know enough about ctypes to use it effectively.
So far, I imagine it working like this: It would support PyQt5 and PySide2. There can be a simple flag that can be passed useQtResource
, which can flag to use a Qt resource instead.
Now, awesomely enough, Qt comes with its own function toHICON
. Great, right? Yes, but unfortunately, for whoever knows what reason, PySide2 (the official Qt Python bindings supported by Nokia) doesn't make QtWin available, whereas PyQt does! If the user is using PyQt, you could probably still make use of the toHICON
function.
--
P.S. for sake of completeness, here's a toHICON
code example.
pixmap = QPixmap(icon_path)
HICON = QtWin.toHICON(QPixmap)
Pretty simple isn't it?
--
Please note that if you choose to use the toHICON
function for PyQt, you will have to include an additional flag useQtapi='pyside2'
(or pyqt5). Why? Because the lovely qtpy
(qtpy is a import library which allows you to abstract away the differences between API's, so you don't have to write or test for multiple APIs, thus, we wouldn't have to specify which API to use) also decided not to include QtWin
! Seriously? Why's everybody forgetting to include important modules in their official distributions?
As for PySide2, as are the cirucmstances, I've found a way to get the raw image data from the resources. QResource(':/resource.ico').data().tobytes()
will get you the raw image data represented as a Python string. Using this, I managed to cobble together a ctypes interface to convert it into a HICON using CreateIconFromResourceEx
. The code looks like the following:
from ctypes import *
from ctypes.wintypes import *
CreateIconFromResourceEx = windll.user32.CreateIconFromResourceEx
size_x, size_y = 32, 32
LR_DEFAULTCOLOR = 0
imgData = QResource(icon_path).data().tobytes()
hicon = CreateIconFromResourceEx(iconData, len(iconData), 1, 0x30000, size_x, size_y, LR_DEFAULTCOLOR)
Looks lovely right? It works, but ... Yeah. It only works on PNG images, not on ICO images. :/ Frustrating. After several searching and API lookups, I found this piece of C code for ICO files.
int offset = LookupIconIdFromDirectoryEx(iconData, TRUE, iconSize, iconSize, LR_DEFAULTCOLOR);
if (offset != 0) {
hIcon = CreateIconFromResourceEx(iconData + offset, 0, TRUE, 0x30000, iconSize, iconSize, LR_DEFAULTCOLOR);
}
I managed to Pythonize it, but, I should warn you, iconData + offset
isn't actually valid, because you cant concatenate a bytes
and an int
data type. I had to use offset.to_bytes(len(offset), byteorder=sys.byteorder)
. Well, this passed the test... No Exceptions, BUT, HICON
is always 0. Anyways, no matter what I try to do, I can't get this to work with an ICO file. Yeah, I could just write the file to the disk and read it again, but that's just UGLY.
CreateIconFromResourceEx = windll.user32.CreateIconFromResourceEx
LookupIconIdFromDirectoryEx = windll.user32.LookupIconIdFromDirectoryEx
size_x, size_y = 32, 32
LR_DEFAULTCOLOR = 0
imgData = QResource(icon_path).data().tobytes()
# works
offset = LookupIconIdFromDirectoryEx(iconData, 1, size_x, size_y, LR_DEFAULTCOLOR)
# "works", as in, won't return an exception, but it ALWAYS returns 0 (using ICO files)
hicon = CreateIconFromResourceEx(iconData + offset.to_bytes(len(offset), byteorder=sys.byteorder), 0, 1, 0x30000, size_x, size_y, LR_DEFAULTCOLOR)
So, this is where I'm at. I can do all this AS LONG as the image is a PNG, not ICO. Also, since I don't have PyQt5, I can't get toHICON
, but that shouldn't be too hard for you to implement.
Any suggestions for fixing this? I'll be glad to throw a pull request if we can solve this. Please help me make this a reality.
-- Speaking of which, your code can only read an ICO image, not an PNG image. It would be nice if it supported PNG as well. As I tested PNG above, I know it works with the system as long as you can convert it to a HICON.
-- Also, I know absolutely nothing about C or ctypes, so please forgive any "obvious mistakes".
Because when you compile Python programs to an exe, and you use Qt, you will want to use the resource system (after all, you don't want raw files lying around when it can become part of the code).
I write my code in Pycharm and import all the libraries from the built-in pip module. I've done the same with win10toast, and as long as I launch the code from Pycharm it works great, but after converting the project into an executable file the notifications are not shown at all.
Here's the code:
import win10toast
toaster = win10toast.ToastNotifier()
toaster.show_toast("Test", "Hello", duration=5, threaded=True)
I was just testing the library's capabilities so it's just a simple code. I've tried converting it to exe with pyinstaller from windows 10 cmd, as well as py2exe.net
Please let me know if it's just a problem that occurrs on my machine or is it to do with the way the library is written or maybe even with the conversion to exe itself. Thank you in advance.
If you're not seeing your toasts while using this module - check "Focus Assist" under System > Focus Assist.
I had to set Focus Assist to "Off" for the toasts to show up.
You may be able to set it back to a stricter setting once you're done coding your app - I'm not there yet.
(I'm primarily a Linux coder, where our systems don't try to be so bloody helpful on their own, so this took me a while to track down. But it works. Yay toast.)
When trying to pack into an exe with pyinstaller many user got an error that something went wrong despite everything working correctly on script. I have found the issue to be the preconfigured icon because pyinstaller does not recognize it as a resource when running as an exe.
Solution:
just pass a custom icon in the toast. you will get an error not finding it if it's not in exe's folder but it will work
Hi, very nifty python package you've compiled here. However, whenever I use multiple toaster messages within a python file (I have one go off for each function in my file), I notice a significant delay when waiting on the next section of the program to run.
I noticed you're using multi-threading to handle the use of multiple messages. Have you considered trying multi-processing instead? Python was not really built to support multi-threading, and it's very hit or miss if it (ever) works as intended. On the other hand, Python was built to support multi-processing. If we could swap the use of multi-threading with processing, I believe this may solve part of the slowdown issue mentioned earlier.
Hello, i wonder if you're still maintaining and keeping an eye on this, if so please respond so i don't waste my time explaining my problem to a wall :)
hey i want to toast 2 notification at the same time
but the code can run 1 toast
when i run 2 toast the first toast is dissapear
I have a simple Qt window it has a button and when you click the button it opens a explorer window for a specific location, when the notification fades out the window closes as well.
Entire Example Script
`class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
@pyqtSlot()
def on_click(self):
print('PyQt5 button click')
subprocess.Popen(r'explorer /open,"C:\WB Resources\"')
toaster = ToastNotifier()
toaster.show_toast("TITLE",
"Python is 10 seconds awsm! and I think that this is the way to go for all information going forward",
icon_path="wbicon.ico",
duration=3)
print('Finished?')
def on_click_cache(self):
path = "C:/Users/XXXXX/AppData/Local/Packages/XXXXXXXXXXXX_XXXXXXXXXXXX/LocalState/cacheddata/"
try:
shutil.rmtree(path)
except:
print('No folder')
self.btn_clearcache.setStyleSheet("background-color: green")
def initUI(self):
QToolTip.setFont(QFont('SansSerif', 10))
btn = QPushButton('Open WBR',self)
btn.setToolTip('This is a <b>QPushButton</b> widget')
btn.resize(150,50)
btn.move(0, 0)
btn.clicked.connect(self.on_click)
self.btn_clearcache = QPushButton('Clear Cache', self)
self.btn_clearcache.setToolTip('Clear the WB App Cache<br><b>THIS IS DESTRUCTIVE</b>')
self.btn_clearcache.resize(150,50)
self.btn_clearcache.move(151, 0)
self.btn_clearcache.setStyleSheet("QPushButton:focus:pressed { background-color: red }")
self.btn_clearcache.clicked.connect(self.on_click_cache)
self.setGeometry(500, 350, 900, 500)
self.setWindowTitle('WB-TOOL')
self.setWindowIcon(QIcon('arrow.png'))
self.show()
if name == 'main':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())`
I ran the code below,
from win10toast import ToastNotifier
toaster = ToastNotifier()
toaster.show_toast("Hello World!!!",
"Python is 10 seconds awsm!",
icon_path=None,
duration=10
)
I got the error below
Traceback (most recent call last):
File "D:\python_workspace\ding.py", line 6, in <module>
duration=10
File "C:\Users\shi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\win10toast\__init__.py", line 98, in show_toast
Shell_NotifyIcon(NIM_ADD, nid)
pywintypes.error: (-2147467259, 'Shell_NotifyIcon', '未指定的错误')
[Finished in 0.7s with exit code 1]
And, when I added
threaded = True
it told me
TypeError: show_toast() got an unexpected keyword argument 'threaded'
It confused me because last time I ran the code, it was absolutely alright. :(
Thanks a lot.
The app GUI always freezes after running a method with toast notif in it... idk but you may give yourself a try...
this method is a member of a tkinter toplevel class which i invoke when user clicks a button
def mymethod(self):
hs = generate_hash()
newpath = f'..\\results\\results{hs}\\'
os.makedirs(newpath)
X = readall_images(self.inputvar.get())
saveall_images(X, newpath, "")
opennotif(newpath, "Done", "open it!")
self.inputvar.set("")
X = None
on the top on it, I import a function I made dedicated for toast notification... the function looks like this:
def opennotif(dir, header, msg):
tst = ToastNotifier()
res = tst.show_toast(str(header), str(msg))
if res is True:
os.system(f'explorer "{dir}"')
In the following code:
from win10toast import ToastNotifier
from time import sleep
notify = ToastNotifier()
notify.show_toast("Testing!", "Hopefully the test goes well...", "info.ico", 10, True)
sleep(4)
notify.show_toast("Testing! #2", "Hopefully the test goes well... (again)", "info.ico", 10, True)
print("End")
Only the first notification shows, and then goes straight to printing "End"
, without showing the second notification.
I am using Python 3.5.4 and Windows 10 Home Fall Creators Update (1709).
Windows 10 Build - 14393.1198
>>> toaster.show_toast("Hello World!", "Python!")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python34\lib\site-packages\win10toast\__init__.py", line 123, in show_toast
UnregisterClass(self.wc.lpszClassName, None)
pywintypes.error: (1412, 'UnregisterClass', 'Class still has open windows.')
After toaster.show_toast was run, the Windows 10 taskbar freezes. Task Manager was required to restart Explorer.exe.
Hi, this looks really great. But in windows 10 the notification does not persist in the action center
I wrote code below:
import pythoncom
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import time
import sys
import pyodbc
from win10toast import ToastNotifier
class AlertSertvice(win32serviceutil.ServiceFramework):
_svc_name_ = "Alert"
_svc_display_name_ = "Alert"
_svc_description_ = "Notification of Windows"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
socket.setdefaulttimeout(600)
def SvcDoRun(self):
#servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, ''))
#self.main()
# def main(self):
rc = None
while rc != win32event.WAIT_OBJECT_0:
try:
toaster = ToastNotifier()
toaster.show_toast('test',duration=10)
except:
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, sys.exc_info()[0]))
rc = win32event.WaitForSingleObject(self.hWaitStop, 10*1000)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
if __name__ == '__main__':
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(AlertSertvice)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(AlertSertvice)
Then compile and install service (python AlertService.py install) then start it.
It dump an error on Event Viewer:
The instance's SvcRun() method failed
Traceback (most recent call last):
File "C:\PYTHON27\lib\site-packages\pypiwin32-219-py2.7-win-amd64.egg\win32serviceutil.py", line 835, in SvcRun
self.SvcDoRun()
File "D:\DB\Python\Test\AlertService.py", line 33, in SvcDoRun
toaster.show_toast('test',duration=10)
File "build\bdist.win-amd64\egg\win10toast_init_.py", line 115, in show_toast
Shell_NotifyIcon(NIM_ADD, nid)
error: (-2147467259, 'Shell_NotifyIcon', 'Unspecified error')
%2: %3
Please help me fix, thank so much
Is this possible? I've tried duration = 0 but that seems to close it after a little while anyway (I'm using threaded notifications if that makes a difference)
Basically I want "high priority" toasts to stack and stay around until the user manually acknowledges them
This is a bit similar to #46 but I was curious how to add images to the notifications. Similar to the news article notifications that you would see on the Windows Action Center, I'd love to be able to attach a picture with sizing dimensions in addition to my message.
The syntax could be something like this:
toaster.show_toast("Today's Weather!",
"It's Cloudy Today",
image_path="http://icon-park.com/imagefiles/simple_weather_icons_cloudy.png",
image_width="600px",
image_height="600px",
icon_path="custom.ico",
duration=10)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.