win32gui: how to get the status bar text of a window? - python

I want to get the status bar text of a window! I'm using win32gui.GetWindowText, but I can't get the status bar text. I just get the title! How can I get the status bar text?
#coding=utf-8
import win32gui
# get main window handle
f = win32gui.FindWindow("TMDIForm",None)
print f,win32gui.GetWindowText(f)
#get child window handle of main window
ex=win32gui.FindWindowEx(f,None,"TPanel",None)
#get child window handle of ex window
exx=win32gui.FindWindowEx(ex,None,"TStatusBar",None)
print exx,win32gui.GetWindowText(exx)

The following should help, you cannot use GetWindowText on a status bar. A status bar usually consists of multiple sub items. To access these use need to use SendMessage with SB_GETTEXT.
#coding=utf-8
import win32gui
import win32api
import win32con
# get main window handle
f = win32gui.FindWindow("TMDIForm",None)
print f,win32gui.GetWindowText(f)
#get child window handle of main window
ex=win32gui.FindWindowEx(f,None,"TPanel",None)
#get child window handle of ex window
exx=win32gui.FindWindowEx(ex,None,"TStatusBar",None)
SB_GETTEXT = win32con.WM_USER + 2
SB_GETTEXTLENGTH = win32con.WM_USER + 3
sub_item = 0
sb_retcode = win32api.SendMessage(exx, SB_GETTEXTLENGTH, sub_item, 0)
sb_type = sb_retcode & 0xFFFF
sb_length = (sb_retcode >> 16) & 0xFFFF
text_buffer = win32gui.PyMakeBuffer(1 + sb_length)
sb_retcode = win32api.SendMessage(exx, SB_GETTEXT, sub_item, text_buffer)
print text_buffer
I have not been able to test this, as I was not able to find a suitable Window.

https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getwindowtexta
If the target window is owned by the current process, GetWindowText causes a WM_GETTEXT message to be sent to the specified window or control. If the target window is owned by another process and has a caption, GetWindowText retrieves the window caption text. If the window does not have a caption, the return value is a null string. This behavior is by design. It allows applications to call GetWindowText without becoming unresponsive if the process that owns the target window is not responding. However, if the target window is not responding and it belongs to the calling application, GetWindowText will cause the calling application to become unresponsive.
To retrieve the text of a control in another process, send a WM_GETTEXT message directly instead of calling GetWindowText.
https://www.programcreek.com/python/example/89831/win32gui.GetClassName
https://github.com/certsocietegenerale/fame_modules/blob/fb7a6fb34124fa2ae026719a0f16767cab731c6d/processing/cutthecrap/cutthecrap.py#L66
# hwnd = your TStatusBar or TToolBar or anything
buffer_len = win32gui.SendMessage(hwnd, win32con.WM_GETTEXTLENGTH, 0, 0) + 1
text = array('b', b'\x00\x00' * buffer_len)
text_len = win32gui.SendMessage(hwnd, win32con.WM_GETTEXT, buffer_len, text)
text = win32gui.PyGetString(text.buffer_info()[0], buffer_len - 1)

Related

How to determine an active screen (monitor) of my Application (window) using python PyQt5?

I am working on an application which is using many widgets (QGroupBox, QVBoxLayout, QHBoxLayout). Initially it was developed on normal HD monitors. But, recently many of us upgraded to 4K resolution monitors. Now some of the buttons and sliders are compressed so small that they are unusable.
Now I tried to make some changes so that the application can be used with both HD and 4K monitors.
I started reading the link below:
https://leomoon.com/journal/python/high-dpi-scaling-in-pyqt5/enter link description here
I thought whenever my window is opened in a particular monitor I can call the following code:
if pixel_x > 1920 and pixel_y > 1080:
Qapp.setAttribute(Qt.AA_EnableHighDpiScaling, True)
Qapp.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
else:
Qapp.setAttribute(Qt.AA_EnableHighDpiScaling, False)
Qapp.setAttribute(Qt.AA_UseHighDpiPixmaps, False)
Then I tried to get the monitor resolution (pixel_x and pixel_y) using below code from using related post here.
import sys, ctypes
user32 = ctypes.windll.user32
user32.SetProcessDPIAware()
screen_width = 0 #78
screen_height = 1 #79
[pixel_x , pixel_y ] = [user32.GetSystemMetrics(screen_width), user32.GetSystemMetrics(screen_height)]
screen_width = 0, screen_height = 1 gives me the resolution of my primary monitor(mostly laptops in our case which are HD). screen_width = 78, screen_height = 79 gives me the combined resolution of virtual machines. But I do not understand how I can dynamically get these values depending upon where my application opened.
My application window is developed in such a way that it will open in the same monitor where it was closed last time. The problem is now I want to get the active monitor resolution whenever my GUI is called and adapt to that resolution. I would be glad if someone can help me out.
I am interested to know if I can call the screen resolution calculation every time that I drag my window from an HD monitor to a 4K monitor and Vice versa.
Edit: I have found something similar in this post here But I could not get much from this.
Edit2: Based on #Joe solution, Primary Screen Detection, Why is my primary screen always my laptop resolution even though I run the application on a 4K screen?
I just tried to get the dpi of all the screens using the code below:
def screen_selection():
app = QApplication(sys.argv)
valid_screens = []
for index, screen_no in enumerate(app.screens()):
screen = app.screens()[index]
dpi = screen.physicalDotsPerInch()
valid_screens.append(dpi)
return valid_screens
One solution I came across is to use a temporary QApplication():
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
# fire up a temporary QApplication
def get_resolution():
app = QtWidgets.QApplication(sys.argv)
print(app.primaryScreen())
d = app.desktop()
print(d.screenGeometry())
print(d.availableGeometry())
print(d.screenCount())
g = d.screenGeometry()
return (g.width(), g.height())
x, y = get_resolution()
if x > 1920 and y > 1080:
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)
else:
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, False)
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, False)
# Now your code ...
This function will detect all attached screens:
# fire up a temporary QApplication
def get_resolution_multiple_screens():
app = QtGui.QGuiApplication(sys.argv)
#QtWidgets.QtGui
all_screens = app.screens()
for s in all_screens:
print()
print(s.name())
print(s.availableGeometry())
print(s.availableGeometry().width())
print(s.availableGeometry().height())
print(s.size())
print(s.size().width())
print(s.size().height())
print()
print('primary:', app.primaryScreen())
print('primary:', app.primaryScreen().availableGeometry().width())
print('primary:', app.primaryScreen().availableGeometry().height())
# now choose one
You can use the hints here and here to get the screen where the application is running.
But I think primaryScreen should also return this:
primaryScreen : QScreen* const
This property holds the primary (or default) screen of the
application.
This will be the screen where QWindows are initially shown, unless
otherwise specified.
(https://doc.qt.io/qt-5/qguiapplication.html#primaryScreen-prop)
Well, after creating the MainWindow, you can just call QMainWindow.screen(). This returns the current screen the MainWindow is on. This would at least allow you to check the screen resolution at the start of your application.
Right now there is no such thing as a screenChangeEvent. However i am sure you can create one by subclassing the MainWindow and overloading the QMainWindow.moveEvent
For example:
class MainWindow(QtWidgets.QMainWindow):
screenChanged = QtCore.pyqtSignal(QtGui.QScreen, QtGui.QScreen)
def moveEvent(self, event):
oldScreen = QtWidgets.QApplication.screenAt(event.oldPos())
newScreen = QtWidgets.QApplication.screenAt(event.pos())
if not oldScreen == newScreen:
self.screenChanged.emit(oldScreen, newScreen)
return super().moveEvent(event)
This checks if the screen has changed. If it has it emits a signal. Now you only need to connect this signal to a function that sets your dpi attributes. The event gives you access to the old and to the new screen.
Warning:
One of the screen can be None at the start of your application because there is no oldScreen when you first start your application. So please check this.
Though i could not get the direct solution I am able to develop a method to get what I was looking. With the help of few links and previous post I am able to achieve. with this post I got an idea of tracking the mouse event.
I developed a method to track all the monitors and respective staring positions. if my variable naming is not appropriate I am happy to accept the changes
def get_screen_resolution():
app = QApplication(sys.argv)
screen_count = QGuiApplication.screens()
resolutions_in_x = []
for index, screen_names in enumerate(screen_count):
resolution = screen_count[index].size()
height = resolution.height()
width = resolution.width()
resolutions_in_x.append(width)
low_resolution_monitors = {}
high_resolution_monitors = {}
for i, wid_res in enumerate(resolutions_in_x):
if wid_res > 1920:
high_resolution_monitors.update({i: wid_res})
else:
low_resolution_monitors.update({'L': wid_res})
temp_value = 0
high_res_monitors_x_position = []
low_res_monitors_x_position = []
for i in range(len(screen_count)):
temp_value = temp_value+resolutions_in_x[i]
if resolutions_in_x[i] in high_resolution_monitors.values():
high_res_monitors_x_position.append(temp_value-resolutions_in_x[i])
else:
low_res_monitors_x_position.append(temp_value-resolutions_in_x[i])
total_width_res = []
pixel_value = 0
first_pixel = 0
for i, wid_value in enumerate(resolutions_in_x):
pixel_value = pixel_value + wid_value
total_width_res.append(tuple((first_pixel, pixel_value-1)))
first_pixel = pixel_value
return high_res_monitors_x_position, low_res_monitors_x_position, total_width_res
def moveEvent(self, event):
screen_pos = self.pos()
screen_dimensions = [screen_pos.x(),screen_pos.y()]
super(MainWindow, self).moveEvent(event)
Window_starting_pt = screen_pos.x()
for i, value in enumerate(self.total_width_res):
if value[0]<=Window_starting_pt+30 <=value[1] or value[0]<=Window_starting_pt-30 <=value[1]: #taking 30pixels as tolerance since widgets are staring at some negative pixel values
if value[0] in self.high_res_monitors_x_position:
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)
else:
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, False)
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, False)
With aboe two functions am able to track my application(window) position and also able to track when ever it is dragged among windows

Populate window in Maya with icons and dynamically adjust depending on window size

I want to create a window in maya, that gets populated with icons from a specific path. I know how to do that, but I also want the icons to adjust dynamically as I change the size of the window.
For example, let's say I have this:
enter image description here
and I want when I resize to get this:
enter image description here
here is a bit of the code I have :
import maya.cmds as cmds
import os
from os import listdir
def UI(*args):
if cmds.window("Test", exists = True):
cmds.deleteUI("Test")
testwindow = cmds.window("Test", t="Test Window", sizeable = 1)
cmds.scrollLayout('srcoll', p = "Test")
cmds.rowColumnLayout("ColLayout", p = "Test", nc = 3)#I imagine the "nc" command is probably useless here, I am just leaving it for testing purposes
cmds.showWindow("Test")
customPath = "C:\Users\$username$\Desktop"
customPathItems = listdir(customPath)
def popUI(*args):
for item in customPathItems:
if item.endswith("_icon.png"):
cmds.iconTextButton(l = item, p = "ColLayout", i = customPath + "/" + item, w = 128, h = 128)
def buildUI(*args):
UI()
popUI()
buildUI()
Any help would be appreciated
What you need is called a Flow layout, where the items inside the layout automatically adjust themselves when the widget is resized.
Here's an example from Qt's documentation that you can fully convert over to Python:
https://doc.qt.io/qt-4.8/qt-layouts-flowlayout-flowlayout-cpp.html
You can also google pyqt flow layout for ones already written in Python.

Why is the Windows prompt unresponsive after using a python curses window?

First of all, I'm a newby in python. Had to take a course of it in college and got hooked by its efficiency.
I have this sticky problem where the Windows 7 prompt becomes unresponsive after using a curses window. In Windows 10 it works well. Note that I'm using the Win7 terminal with its default settings. In my code I create a curses window to show 2 simultaneous progress bars, each for a file download. I implemented this by passing the curses window to a FileDownload class (one class instance for each download) that handles its progress bar inside this window. Oddly, in Windows 7 when the downloads are done and the control returns to the prompt, it becomes unresponsive to the keyboard. I worked around this by invoking curses.endwin() after using the window, but this causes the prompt to display all the way down the screen buffer, what hides the curses window.
Here is my code. Any ideas are greatly appreciated. Thanks!
# Skeleton version for simulations.
# Downloads 2 files simultaneously and shows a progress bar for each.
# Each file download is a FileDownload object that interacts with a
# common curses window passed as an argument.
import requests, math, threading, curses, datetime
class FileDownload:
def __init__(self, y_pos, window, url):
# Y position of the progress bar in the download queue window.
self.__bar_pos = int(y_pos)
self.__progress_window = window
self.__download_url = url
# Status of the file download object.
self.__status = "queued"
t = threading.Thread(target=self.__file_downloader)
t.start()
# Downloads selected file and handles its progress bar.
def __file_downloader(self):
file = requests.get(self.__download_url, stream=True)
self.__status = "downloading"
self.__progress_window.addstr(self.__bar_pos + 1, 1, "0%" + " " * 60 + "100%")
size = int(file.headers.get('content-length'))
win_prompt = "Downloading " + format(size, ",d") + " Bytes:"
self.__progress_window.addstr(self.__bar_pos, 1, win_prompt)
file_name = str(datetime.datetime.now().strftime("%Y-%m-%d_%H.%M.%d"))
dump = open(file_name, "wb")
# Progress bar length.
bar_space = 58
# Same as an index.
current_iteration = 0
# Beginning position of the progress bar.
progress_position = 4
# How many iterations will be needed (in chunks of 1 MB).
iterations = math.ceil(size / 1024 ** 2)
# Downloads the file in 1MB chunks.
for block in file.iter_content(1024 ** 2):
dump.write(block)
# Progress bar controller.
current_iteration += 1
step = math.floor(bar_space / iterations)
if current_iteration > 1:
progress_position += step
if current_iteration == iterations:
step = bar_space - step * (current_iteration - 1)
# Updates the progress bar.
self.__progress_window.addstr(self.__bar_pos + 1, progress_position,
"#" * step)
dump.close()
self.__status = "downloaded"
# Returns the current status of the file download ("queued", "downloading" or
# "downloaded").
def get_status(self):
return self.__status
# Instantiates each file download.
def files_downloader():
# Creates curses window.
curses.initscr()
win = curses.newwin(8, 70)
win.border(0)
win.immedok(True)
# Download URLs.
urls = ["http://ipv4.download.thinkbroadband.com/10MB.zip",
"http://ipv4.download.thinkbroadband.com/5MB.zip"]
downloads_dct = {}
for n in range(len(urls)):
# Progress bar position in the window for the file.
y_pos = n * 4 + 1
downloads_dct[n + 1] = FileDownload(y_pos, win, urls[n])
# Waits for all files to be downloaded before passing control of the terminal
# to the user.
all_downloaded = False
while not all_downloaded:
all_downloaded = True
for key, file_download in downloads_dct.items():
if file_download.get_status() != "downloaded":
all_downloaded = False
# Prevents the prompt from returning inside the curses window.
win.addstr(7, 1, "-")
# This solves the unresponsive prompt issue but hides the curses window if the screen buffer
# is higher than the window size.
# curses.endwin()
while input("\nEnter to continue: ") == "":
files_downloader()
Perhaps you're using cygwin (and ncurses): ncurses (like any other curses implementation) changes the terminal I/O mode when it is running. The changes that you probably are seeing is that
input characters are not echoed
you have to type controlJ to end an input line, rather than just Enter
output is not flushed automatically at the end of each line
It makes those changes to allow it to read single characters and also to use the terminal more efficiently.
To change back to the terminal's normal I/O mode, you would use the endwin function. The reset_shell_mode function also would be useful.
Further reading:
endwin (ncurses manual)
reset_shell_mode (ncurses manual)

raw_input stops GUI from appearing

I have written a program in Python that allow me to change the names of many files all at once. I have one issue that is quite odd.
When I use raw_input to get my desired extension, the GUI will not launch. I don't get any errors, but the window will never appear.
I tried using raw_input as a way of getting a file extension from the user to build the file list. This program will works correctly when raw_input is not used.The section of code that I am referring to is in my globList function. For some reason when raw_imput is used the window will not launch.
import os
import Tkinter
import glob
from Tkinter import *
def changeNames(dynamic_entry_list, filelist):
for index in range(len(dynamic_entry_list)):
if(dynamic_entry_list[index].get() != filelist[index]):
os.rename(filelist[index], dynamic_entry_list[index].get())
print "The files have been updated!"
def drawWindow(filelist):
dynamic_entry_list = []
my_row = 0
my_column = 0
for name in filelist:
my_column = 0
label = Tkinter.Label(window, text = name, justify = RIGHT)
label.grid(row = my_row, column = my_column)
my_column = 1
entry = Entry(window, width = 50)
dynamic_entry_list.append(entry)
entry.insert(0, name)
entry.grid(row = my_row, column = my_column)
my_row += 1
return dynamic_entry_list
def globList(filelist):
#ext = raw_input("Enter the file extension:")
ext = ""
desired = '*' + ext
for name in glob.glob(desired):
filelist.append(name)
filelist = []
globList(filelist)
window = Tkinter.Tk()
user_input = drawWindow(filelist)
button = Button(window, text = "Change File Names", command = (lambda e=user_input: changeNames(e, filelist)))
button.grid(row = len(filelist) + 1 , column = 1)
window.mainloop()
Is this a problem with raw_input?
What would be a good solution to the problem?
This is how tkinter is defined to work. It is single threaded, so while it's waiting for user input it's truly waiting. mainloop must be running so that the GUI can respond to events, including internal events such as requests to draw the window on the screen.
Generally speaking, you shouldn't be mixing a GUI with reading input from stdin. If you're creating a GUI, get the input from the user via an entry widget. Or, get the user input before creating the GUI.
A decent tutorial on popup dialogs can be found on the effbot site: http://effbot.org/tkinterbook/tkinter-dialog-windows.htm

Unable to use wx.NotificationMessage properly with wxPython

I recently upgraded to the development release of wxPython (wxPython 2.9.2.4) since I needed the functionality of wx.NotificationMessage within my application. I have been trying unsuccessfully to create notification bubbles on certain user events due to something I think might be a possible bug. Before submitting such bug, I wanted to go ahead and ask the people of the mailing list what they think might be the problem and hopefully find a solution from within my code.
Here is the code I have used:
import wx, sys
app = wx.PySimpleApp()
class TestTaskBarIcon(wx.TaskBarIcon):
def __init__(self):
wx.TaskBarIcon.__init__(self)
# create a test icon
bmp = wx.EmptyBitmap(16, 16)
dc = wx.MemoryDC(bmp)
dc.SetBrush(wx.RED_BRUSH)
dc.Clear()
dc.SelectObject(wx.NullBitmap)
testicon = wx.EmptyIcon()
testicon.CopyFromBitmap(bmp)
self.SetIcon(testicon)
self.Bind(wx.EVT_TASKBAR_LEFT_UP, lambda e: (self.RemoveIcon(),sys.exit()))
wx.NotificationMessage("", "Hello world!").Show()
icon = TestTaskBarIcon()
app.MainLoop()
On my Windows 7 computer, the code creates a small white task bar icon and creates a popup with the phrase "Hello World!". The problem? The message is not on my icon. Another icon is being created and the message is being placed there.
See this image:
http://www.pasteall.org/pic/18068">
What I thought was that this is probably due to the fact that I have passed no parent parameter on line 22:
wx.NotificationMessage("", "Hello world!").Show()
Here is what I changed it to:
wx.NotificationMessage("", "Hello world!", self).Show()
Where 'self' refers to the task bar icon. When I do that, I get an error:
Traceback (most recent call last):
File "C:\Python27\testnotificationmessage.py", line 24, in <module>
icon = TestTaskBarIcon()
File "C:\Python27\testnotificationmessage.py", line 22, in __init__
wx.NotificationMessage("", "Hello world!", self).Show()
File "C:\Python27\lib\site-packages\wx-2.9.2-msw\wx\_misc.py", line 1213, in __init__
_misc_.NotificationMessage_swiginit(self,_misc_.new_NotificationMessage(*args))
TypeError: in method 'new_NotificationMessage', expected argument 3 of type 'wxWindow *'
What's going on? If I remove that argument, I don't get my result, if I add the argument, I get an error! How am I supposed to use wx.NotificationMessage with a wx.TaskBarIcon!
Please help! I hope I've provided enough details. Please comment if you need more!
I would not recommend using 2.9 just yet. I have encountered some strange bugs when trying it out.
You can have the same functionality in 2.8. I am using somewhat modified code that I have found some time ago.
import wx, sys
try:
import win32gui #, win32con
WIN32 = True
except:
WIN32 = False
class BalloonTaskBarIcon(wx.TaskBarIcon):
"""
Base Taskbar Icon Class
"""
def __init__(self):
wx.TaskBarIcon.__init__(self)
self.icon = None
self.tooltip = ""
def ShowBalloon(self, title, text, msec = 0, flags = 0):
"""
Show Balloon tooltip
#param title - Title for balloon tooltip
#param msg - Balloon tooltip text
#param msec - Timeout for balloon tooltip, in milliseconds
#param flags - one of wx.ICON_INFORMATION, wx.ICON_WARNING, wx.ICON_ERROR
"""
if WIN32 and self.IsIconInstalled():
try:
self.__SetBalloonTip(self.icon.GetHandle(), title, text, msec, flags)
except Exception:
pass # print(e) Silent error
def __SetBalloonTip(self, hicon, title, msg, msec, flags):
# translate flags
infoFlags = 0
if flags & wx.ICON_INFORMATION:
infoFlags |= win32gui.NIIF_INFO
elif flags & wx.ICON_WARNING:
infoFlags |= win32gui.NIIF_WARNING
elif flags & wx.ICON_ERROR:
infoFlags |= win32gui.NIIF_ERROR
# Show balloon
lpdata = (self.__GetIconHandle(), # hWnd
99, # ID
win32gui.NIF_MESSAGE|win32gui.NIF_INFO|win32gui.NIF_ICON, # flags: Combination of NIF_* flags
0, # CallbackMessage: Message id to be pass to hWnd when processing messages
hicon, # hIcon: Handle to the icon to be displayed
'', # Tip: Tooltip text
msg, # Info: Balloon tooltip text
msec, # Timeout: Timeout for balloon tooltip, in milliseconds
title, # InfoTitle: Title for balloon tooltip
infoFlags # InfoFlags: Combination of NIIF_* flags
)
win32gui.Shell_NotifyIcon(win32gui.NIM_MODIFY, lpdata)
self.SetIcon(self.icon, self.tooltip) # Hack: because we have no access to the real CallbackMessage value
def __GetIconHandle(self):
"""
Find the icon window.
This is ugly but for now there is no way to find this window directly from wx
"""
if not hasattr(self, "_chwnd"):
try:
for handle in wx.GetTopLevelWindows():
if handle.GetWindowStyle():
continue
handle = handle.GetHandle()
if len(win32gui.GetWindowText(handle)) == 0:
self._chwnd = handle
break
if not hasattr(self, "_chwnd"):
raise Exception
except:
raise Exception, "Icon window not found"
return self._chwnd
def SetIcon(self, icon, tooltip = ""):
self.icon = icon
self.tooltip = tooltip
wx.TaskBarIcon.SetIcon(self, icon, tooltip)
def RemoveIcon(self):
self.icon = None
self.tooltip = ""
wx.TaskBarIcon.RemoveIcon(self)
# ===================================================================
app = wx.PySimpleApp()
class TestTaskBarIcon(BalloonTaskBarIcon):
def __init__(self):
wx.TaskBarIcon.__init__(self)
# create a test icon
bmp = wx.EmptyBitmap(16, 16)
dc = wx.MemoryDC(bmp)
dc.SetBrush(wx.RED_BRUSH)
dc.Clear()
dc.SelectObject(wx.NullBitmap)
testicon = wx.EmptyIcon()
testicon.CopyFromBitmap(bmp)
self.SetIcon(testicon)
self.Bind(wx.EVT_TASKBAR_LEFT_UP, lambda e: (self.RemoveIcon(),sys.exit()))
self.ShowBalloon("", "Hello world!")
icon = TestTaskBarIcon()
app.MainLoop()
There is an undocumented hidden method in TaskBarIcon called ShowBalloon which is only implemented for Windows.
From the source:
def ShowBalloon(*args, **kwargs):
"""
ShowBalloon(self, String title, String text, unsigned int msec=0, int flags=0) -> bool
Show a balloon notification (the icon must have been already
initialized using SetIcon). Only implemented for Windows.
title and text are limited to 63 and 255 characters respectively, msec
is the timeout, in milliseconds, before the balloon disappears (will
be clamped down to the allowed 10-30s range by Windows if it's outside
it) and flags can include wxICON_ERROR/INFO/WARNING to show a
corresponding icon
Returns True if balloon was shown, False on error (incorrect parameters
or function unsupported by OS)
"""
return _windows_.TaskBarIcon_ShowBalloon(*args, **kwargs)
I tested it on Windows with wxPython 2.9.4.0 and it works well.

Categories

Resources