How to add OSX menu bar icon with wxPython - python

I would like to add an icon to the OSX menu bar at the top of the screen using wxPython. I have tried wx.TaskBarIcon, which adds a System Tray icon in Windows, but this doesn't work - it changes the Dock icon for the app instead. Does anyone know how to do this?

It seems that with wxPython2.9-osx-cocoa-py2.7 you can in fact put up a menubar icon. It looks like you can also call PopupMenu() on TaskBarIcon to attach a menu, which you should be able to use to create a full blown OSX menu bar application.
import wx
class TaskBarFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, style=wx.FRAME_NO_TASKBAR |
wx.NO_FULL_REPAINT_ON_RESIZE)
self.tbicon = wx.TaskBarIcon()
icon = wx.Icon('myicon.ico', wx.BITMAP_TYPE_ICO)
self.tbicon.SetIcon(icon, '')
app = wx.App(False)
frame = TaskBarFrame(None)
frame.Show(False)
app.MainLoop()

Answer provided here on Google Groups - in summary, you can't do it.

It seems now you can:
http://wiki.wxpython.org/Custom%20Mac%20OsX%20Dock%20Bar%20Icon?highlight=%28wx%5C.TaskBarIcon%29
just copy and paste the code and run it ;)
#!/usr/bin/env pythonw
import wx
import wx.lib.embeddedimage
WXPdemo = wx.lib.embeddedimage.PyEmbeddedImage(
"iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAAAWlJ"
"REFUWIW1V1sSwjAIBMebeBU9db2KZ8EPmxbCI4TUnXGskWaXDQktwhjErjERP4XRhER08iPi"
"5SKiyQR5JyI7xxB3j7wn5GI6V2hFxM0gJtjYANFBiIjQu7L/1lYlwR0QxLDZhE0II1+CtwRC"
"RI8riBva7DL7CC9VAwDbbxwKtdDXwBi7K+1zCP99T1vDFedd8FBwYd6BCAUXuACEF7QsbET/"
"FaHs+gDQw4vOLNHkMojAnTw8nlNipIiwmR0DCXJbjCXkFCAL23BnpQgRWt1EMbyujCK9AZzZ"
"f+b3sX0oSqJQ6EorFeT4NiL6Wtj0+LXnQAzThYoAAsN6ehqR3sHExmcEqGeFApQLcTvm5Kt9"
"wkHGgb+RZwSkyc1dwOcpCtCoNKSz6FRCUQ3o7Nn+5Y+Lg+y5CIXlcyAk99ziiQS32+svz/UY"
"vClJoLpIC8gi+VwwfDecEiEtT/WZTJDf94uk1Ru8vbz0cvoF7S2DnpeVL9UAAAAASUVORK5C"
"YII=")
class DemoTaskBarIcon(wx.TaskBarIcon):
TBMENU_RESTORE = wx.NewId()
TBMENU_CLOSE = wx.NewId()
TBMENU_CHANGE = wx.NewId()
TBMENU_REMOVE = wx.NewId()
def __init__(self, frame):
wx.TaskBarIcon.__init__(self)
self.frame = frame
# Set the image
icon = self.MakeIcon(WXPdemo.GetImage())
self.SetIcon(icon, "wxPython Demo")
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)
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 wxPython Demo")
menu.Append(self.TBMENU_CLOSE, "Close wxPython Demo")
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.Close)
class MainFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, title="Hello World")
self.tbicon = DemoTaskBarIcon(self)
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
def OnCloseWindow(self, evt):
self.tbicon.Destroy()
evt.Skip()
app = wx.App(redirect=False)
frame = MainFrame(None)
frame.Show(True)
app.MainLoop()

Related

wxPython: Populate menu in sub panel

I have a wx application where the main frame has several sub panels. I'd like to have a menu bar in the main frame, where each of the menus is associated with a panel. This means that the creation of menu items and binding them to event handlers should be done in the individual panels and not in the main frame. Here is a minimal example:
import wx
class myPanel1(wx.Panel):
def __init__(self, parent, menubar):
super().__init__(parent=parent)
menu = wx.Menu()
menuAction1 = menu.Append(wx.ID_ANY, 'Action1')
menuAction2 = menu.Append(wx.ID_ANY, 'Action2')
menubar.Append(menu, '&Actions')
# This does not work because the EVT_MENU is only seen by the main frame(?)
self.Bind(wx.EVT_MENU, self.onAction1, menuAction1)
self.Bind(wx.EVT_MENU, self.onAction2, menuAction2)
def onAction1(self, event):
print('Hello1')
def onAction2(self, event):
print('Hello2')
class mainWindow(wx.Frame):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.menubar = wx.MenuBar()
# There are more panels in my actual program
self.panel1 = myPanel1(self, self.menubar)
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(self.panel1, flag=wx.EXPAND, proportion=1)
self.SetSizerAndFit(sizer)
self.SetMenuBar(self.menubar)
self.Layout()
class myApp(wx.App):
def OnInit(self):
frame = mainWindow(parent=None, title='Title')
self.SetTopWindow(frame)
frame.Show()
return True
if __name__ == '__main__':
app = myApp()
app.MainLoop()
The problem is now that myPanel1.onAction1 is not called because the menu event from the main frame does not propagate to the sub panel.
Is there any neat way to do this?
Meanwhile I've found the answer myself. It's as simple as changing
self.Bind(wx.EVT_MENU, self.onAction1, menuAction1)
in myPanel1.__init__ to
self.GetParent().Bind(wx.EVT_MENU, self.onAction1, menuAction1)
Anyway, thanks everyone who thought about this question for their effort.

How can I develop Windows PC background tray apps using Python? [duplicate]

I'd just need a quick example on how to easily put an icon with python on my systray. This means: I run the program, no window shows up, just a tray icon (I've got a png file) shows up in the systray and when I right-click on it a menu appears with some options (and when I click on an option, a function is run).
Is that possible? I don't need any window at all...
Examples / code snippets are REALLY appreciated! :D
For Windows & Gnome
Here ya go! wxPython is the bomb. Adapted from the source of my Feed Notifier application.
import wx
TRAY_TOOLTIP = 'System Tray Demo'
TRAY_ICON = 'icon.png'
def create_menu_item(menu, label, func):
item = wx.MenuItem(menu, -1, label)
menu.Bind(wx.EVT_MENU, func, id=item.GetId())
menu.AppendItem(item)
return item
class TaskBarIcon(wx.TaskBarIcon):
def __init__(self):
super(TaskBarIcon, self).__init__()
self.set_icon(TRAY_ICON)
self.Bind(wx.EVT_TASKBAR_LEFT_DOWN, self.on_left_down)
def CreatePopupMenu(self):
menu = wx.Menu()
create_menu_item(menu, 'Say Hello', self.on_hello)
menu.AppendSeparator()
create_menu_item(menu, 'Exit', self.on_exit)
return menu
def set_icon(self, path):
icon = wx.IconFromBitmap(wx.Bitmap(path))
self.SetIcon(icon, TRAY_TOOLTIP)
def on_left_down(self, event):
print 'Tray icon was left-clicked.'
def on_hello(self, event):
print 'Hello, world!'
def on_exit(self, event):
wx.CallAfter(self.Destroy)
def main():
app = wx.PySimpleApp()
TaskBarIcon()
app.MainLoop()
if __name__ == '__main__':
main()
2018 version
import wx.adv
import wx
TRAY_TOOLTIP = 'Name'
TRAY_ICON = 'icon.png'
def create_menu_item(menu, label, func):
item = wx.MenuItem(menu, -1, label)
menu.Bind(wx.EVT_MENU, func, id=item.GetId())
menu.Append(item)
return item
class TaskBarIcon(wx.adv.TaskBarIcon):
def __init__(self, frame):
self.frame = frame
super(TaskBarIcon, self).__init__()
self.set_icon(TRAY_ICON)
self.Bind(wx.adv.EVT_TASKBAR_LEFT_DOWN, self.on_left_down)
def CreatePopupMenu(self):
menu = wx.Menu()
create_menu_item(menu, 'Site', self.on_hello)
menu.AppendSeparator()
create_menu_item(menu, 'Exit', self.on_exit)
return menu
def set_icon(self, path):
icon = wx.Icon(path)
self.SetIcon(icon, TRAY_TOOLTIP)
def on_left_down(self, event):
print ('Tray icon was left-clicked.')
def on_hello(self, event):
print ('Hello, world!')
def on_exit(self, event):
wx.CallAfter(self.Destroy)
self.frame.Close()
class App(wx.App):
def OnInit(self):
frame=wx.Frame(None)
self.SetTopWindow(frame)
TaskBarIcon(frame)
return True
def main():
app = App(False)
app.MainLoop()
if __name__ == '__main__':
main()
wx.PySimpleApp deprecated, here's how to use wx.App instead
Took me while to figure this out so I thought I'd share. wx.PySimpleApp is deprecated in wxPython 2.9 and beyond. Here's FogleBird's original script using wx.App instead.
import wx
TRAY_TOOLTIP = 'System Tray Demo'
TRAY_ICON = 'icon.png'
def create_menu_item(menu, label, func):
item = wx.MenuItem(menu, -1, label)
menu.Bind(wx.EVT_MENU, func, id=item.GetId())
menu.AppendItem(item)
return item
class TaskBarIcon(wx.TaskBarIcon):
def __init__(self, frame):
self.frame = frame
super(TaskBarIcon, self).__init__()
self.set_icon(TRAY_ICON)
self.Bind(wx.EVT_TASKBAR_LEFT_DOWN, self.on_left_down)
def CreatePopupMenu(self):
menu = wx.Menu()
create_menu_item(menu, 'Say Hello', self.on_hello)
menu.AppendSeparator()
create_menu_item(menu, 'Exit', self.on_exit)
return menu
def set_icon(self, path):
icon = wx.IconFromBitmap(wx.Bitmap(path))
self.SetIcon(icon, TRAY_TOOLTIP)
def on_left_down(self, event):
print 'Tray icon was left-clicked.'
def on_hello(self, event):
print 'Hello, world!'
def on_exit(self, event):
wx.CallAfter(self.Destroy)
self.frame.Close()
class App(wx.App):
def OnInit(self):
frame=wx.Frame(None)
self.SetTopWindow(frame)
TaskBarIcon(frame)
return True
def main():
app = App(False)
app.MainLoop()
if __name__ == '__main__':
main()
If you can guarantee windows and you do not want to introduce the heavy dependencies of wx, you can do this with the pywin32 extensions.
Also see this question.
For Ubuntu
class TrayIcon:
def init():
iconPath = {"Windows":os.path.expandvars("%PROGRAMFILES%/MyProgram/icon.png"),
"Linux":"/usr/share/icons/myprogramicon.png"}
if platform.system()=="Linux":
import gtk
import appindicator # Ubuntu apt-get install python-appindicator
# Create an application indicator
try:
gtk.gdk.threads_init()
gtk.threads_enter()
icon = iconPath[platform.system()]
indicator = appindicator.Indicator("example-simple-client", "indicator-messages", appindicator.CATEGORY_APPLICATION_STATUS)
indicator.set_icon(icon)
indicator.set_status (appindicator.STATUS_ACTIVE)
indicator.set_attention_icon ("indicator-messages-new")
menu = gtk.Menu()
menuTitle = "Quit"
menu_items = gtk.MenuItem(menuTitle)
menu.append(menu_items)
menu_items.connect("activate", TrayIcon.QuitApp, menuTitle)
menu_items.show()
menuTitle = "About My Program"
menu_items = gtk.MenuItem(menuTitle)
menu.append(menu_items)
menu_items.connect("activate", TrayIcon.AboutApp, menuTitle)
menu_items.show()
indicator.set_menu(menu)
except:
pass
# Run the app indicator on the main thread.
try:
t = threading.Thread(target=gtk.main)
t.daemon = True # this means it'll die when the program dies.
t.start()
#gtk.main()
except:
pass
finally:
gtk.threads_leave()
#staticmethod
def AboutApp(a1,a2):
gtk.threads_enter()
dialog = gtk.Dialog("About",
None,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
label = gtk.Label("My Program v0.0.1, (C)opyright ME 2015. All rights reserved.")
dialog.vbox.pack_start(label)
label.show()
label2 = gtk.Label("example.com\n\nFor more support contact me#gmail.com")
label2.show()
dialog.action_area.pack_end(label2)
response = dialog.run()
dialog.destroy()
gtk.threads_leave()
#staticmethod
def QuitApp(a1, a2):
sys.exit(0)
Cross-Platform
See PyQt: Show menu in a system tray application
There is a package called pystray (bad name, just say it out loud) but works like a charm and is more lightweight than wx or Qt. These are the links:
https://pystray.readthedocs.io/en/latest/index.html
https://pypi.org/project/pystray/
Yes. There is a cross-platform example on wiki.wxpython.org that I've tested with python 2.7 (minconda install) on macOS High Sierra (10.13.3), Windows 7, and gnome 3/centos7. It is here (ignore the page title):
https://wiki.wxpython.org/Custom%20Mac%20OsX%20Dock%20Bar%20Icon
Small mods are needed for python 3.6:
you must import wx.adv
wx.TaskBarIcon becomes wx.adv.TaskBarIcon
wx.IconFromBitmap becomes wx.Icon
Gnome 3 required installation of TopIcons Plus.
Since you don't want to have the window display (" no window shows up, just a tray icon"), simply comment out the following line (though you still want to keep the wx.Frame parent):
frame.Show(True)
And since you want to use your own .png icon, remove the WXPdemo image and embeddedimage stuff and replace
icon = self.MakeIcon(WXPdemo.GetImage())
with, for example
icon = wx.Icon('icon.png')
In my experience, this will provide a good start for adapting or extending further.
An alternative if you are trying to run a python based program in the background you can run it as a service. Check out this active state recipe its pretty useful. I believe one of the options is to convert your application to exe with py2exe or pyinstall.
http://code.activestate.com/recipes/551780/
For an example, refer to this thread -> wx question.
wxPython "classic" -> [new API] wxPython 'Phoenix' (Py3)

Creating ScrolledWindow in wxPython

I am trying to make a ScrolledWindow that can scroll over a grid of images, but the scrollbar isn't appearing. wxWidgets documentation says:
The most automatic and newest way [to set the scrollbars in wxScrolledWindow] is to simply let sizers determine the scrolling area. This is now the default when you set an interior sizer into a wxScrolledWindow with wxWindow::SetSizer. The scrolling area will be set to the size requested by the sizer and the scrollbars will be assigned for each orientation according to the need for them and the scrolling increment set by wxScrolledWindow::SetScrollRate
So I try to set the sizer of my ScrolledWindow with a GridSizer but it's not working. The code:
import wx
class MyFrame(wx.Frame):
def __init__(self, parent, id=-1,title="",pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE,
name="frame"):
wx.Frame.__init__(self,parent,id,title,pos,size,style,name)
self.panel = wx.ScrolledWindow(self,wx.ID_ANY)
menuBar = wx.MenuBar()
menu1 = wx.Menu()
m = menu1.Append(wx.NewId(), "&Blah", "Show Pictures")
menuBar.Append(menu1,"&Blah")
self.Bind(wx.EVT_MENU,self.OnInit,m)
self.SetMenuBar(menuBar)
def OnInit(self, event):
sizer = wx.GridSizer(rows=7,cols=3)
filenames = []
for i in range(20):
filenames.append("img"+str(i)+".png")
for fn in filenames:
img = wx.Image(fn,wx.BITMAP_TYPE_ANY)
sizer.Add(wx.StaticBitmap(self.panel,wx.ID_ANY,wx.BitmapFromImage(img)))
self.panel.SetSizer(sizer)
class MyApp(wx.App):
def OnInit(self):
self.frame = MyFrame(parent=None,title="Frame")
self.frame.Show()
self.SetTopWindow(self.frame)
return True
if __name__ == "__main__":
app = MyApp()
app.MainLoop()
Insert this
self.panel.SetScrollbars(1, 1, 1, 1)
after self.panel = wx.ScrolledWindow(self,wx.ID_ANY)
If you want some info on the SetScrollBars method then look at this wxwidgets documentation page

Scrolling through a `wx.ScrolledPanel` with the mouse wheel and arrow keys

In my wxPython application I've created a wx.ScrolledPanel, in which there is a big wx.StaticBitmap that needs to be scrolled.
The scroll bars do appear and I can scroll with them, but I'd also like to be able to scroll with the mouse wheel and the arrow keys on the keyboard. It would be nice if the "Home", "Page Up", and those other keys would also function as expected.
How do I do this?
UPDATE:
I see the problem. The ScrolledPanel is able to scroll, but only when it is under focus. Problem is, how do I get to be under focus? Even clicking on it doesn't do it. Only if I put a text control inside of it I can focus on it and thus scroll with the wheel. But I don't want to have a text control in it. So how do I make it focus?
UPDATE 2:
Here is a code sample that shows this phenomena. Uncomment to see how a text control makes the mouse wheel work.
import wx, wx.lib.scrolledpanel
class MyFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
scrolled_panel = \
wx.lib.scrolledpanel.ScrolledPanel(parent=self, id=-1)
scrolled_panel.SetupScrolling()
text = "Ooga booga\n" * 50
static_text=wx.StaticText(scrolled_panel, -1, text)
sizer=wx.BoxSizer(wx.VERTICAL)
sizer.Add(static_text, wx.EXPAND, 0)
# Uncomment the following 2 lines to see how adding
# a text control to the scrolled panel makes the
# mouse wheel work.
#
#text_control=wx.TextCtrl(scrolled_panel, -1)
#sizer.Add(text_control, wx.EXPAND, 0)
scrolled_panel.SetSizer(sizer)
self.Show()
if __name__=="__main__":
app = wx.PySimpleApp()
my_frame=MyFrame(None, -1)
#import cProfile; cProfile.run("app.MainLoop()")
app.MainLoop()
Problem is on window Frame gets the focus and child panel is not getting the Focus (on ubuntu linux it is working fine). Workaround can be as simple as to redirect Frame focus event to set focus to panel e.g.
import wx, wx.lib.scrolledpanel
class MyFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
self.panel = scrolled_panel = \
wx.lib.scrolledpanel.ScrolledPanel(parent=self, id=-1)
scrolled_panel.SetupScrolling()
text = "Ooga booga\n" * 50
static_text=wx.StaticText(scrolled_panel, -1, text)
sizer=wx.BoxSizer(wx.VERTICAL)
sizer.Add(static_text, wx.EXPAND, 0)
scrolled_panel.SetSizer(sizer)
self.Show()
self.panel.SetFocus()
scrolled_panel.Bind(wx.EVT_SET_FOCUS, self.onFocus)
def onFocus(self, event):
self.panel.SetFocus()
if __name__=="__main__":
app = wx.PySimpleApp()
my_frame=MyFrame(None, -1)
app.MainLoop()
or onmouse move over panel, set focus to it, and all keys + mousewheeel will start working e.g.
import wx, wx.lib.scrolledpanel
class MyFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
self.panel = scrolled_panel = \
wx.lib.scrolledpanel.ScrolledPanel(parent=self, id=-1)
scrolled_panel.SetupScrolling()
scrolled_panel.Bind(wx.EVT_MOTION, self.onMouseMove)
text = "Ooga booga\n" * 50
static_text=wx.StaticText(scrolled_panel, -1, text)
sizer=wx.BoxSizer(wx.VERTICAL)
sizer.Add(static_text, wx.EXPAND, 0)
scrolled_panel.SetSizer(sizer)
self.Show()
def onMouseMove(self, event):
self.panel.SetFocus()
if __name__=="__main__":
app = wx.PySimpleApp()
my_frame=MyFrame(None, -1)
app.MainLoop()
Here's an example that should do what you want, I hope. (Edit: In retrospect, this doesnt' quite work, for example, when there are two scrolled panels... I'll leave it up here though so peole can downvote it or whatever.) Basically I put everything in a panel inside the frame (generally a good idea), and then set the focus to this main panel.
import wx
import wx, wx.lib.scrolledpanel
class MyFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
main_panel = wx.Panel(self, -1)
main_panel.SetBackgroundColour((150, 100, 100))
self.main_panel = main_panel
scrolled_panel = \
wx.lib.scrolledpanel.ScrolledPanel(parent=main_panel, id=-1)
scrolled_panel.SetupScrolling()
self.scrolled_panel = scrolled_panel
cpanel = wx.Panel(main_panel, -1)
cpanel.SetBackgroundColour((100, 150, 100))
b = wx.Button(cpanel, -1, size=(40,40))
self.Bind(wx.EVT_BUTTON, self.OnClick, b)
self.b = b
text = "Ooga booga\n" * 50
static_text=wx.StaticText(scrolled_panel, -1, text)
main_sizer=wx.BoxSizer(wx.VERTICAL)
main_sizer.Add(scrolled_panel, 1, wx.EXPAND)
main_sizer.Add(cpanel, 1, wx.EXPAND)
main_panel.SetSizer(main_sizer)
text_sizer=wx.BoxSizer(wx.VERTICAL)
text_sizer.Add(static_text, 1, wx.EXPAND)
scrolled_panel.SetSizer(text_sizer)
self.main_panel.SetFocus()
self.Show()
def OnClick(self, evt):
print "click"
if __name__=="__main__":
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1)
frame.Show(True)
self.SetTopWindow(frame)
return True
app = MyApp(0)
app.MainLoop()
For keyboard control, like setting action from the home key, I think you'll need to bind to those events, and respond appropriately, such as using mypanel.Scroll(0,0) for the home key (and remember to call evt.Skip() for the keyboard events you don't act on). (Edit: I don't think there are any default key bindings for scrolling. I'm not sure I'd want any either, for example, what should happen if there's a scrolled panel within a scrolled panel?)

wxpython drag&drop focus problem

I'd like to implement drag&drop in wxPython that works in similar way that in WordPad/Eclipse etc. I mean the following:
when something is being dropped to WordPad, WordPad window is on top with focus and text is added. In Eclipse editor text is pasted, Eclipse window gains focus and is on top.
When I implement drag&drop using wxPython target window is not brought to front. I implemented drag&drop in similar way to (drag):
import wx
class DragFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
self.tree = wx.TreeCtrl(self, wx.ID_ANY)
root = self.tree.AddRoot("root item")
self.tree.AppendItem(root, "child 1")
self.tree.Bind(wx.EVT_TREE_BEGIN_DRAG, self.__onBeginDrag)
def __onBeginDrag(self, event):
tdo = wx.PyTextDataObject(self.tree.GetItemText(event.GetItem()))
dropSource = wx.DropSource(self.tree)
dropSource.SetData(tdo)
dropSource.DoDragDrop(True)
app = wx.PySimpleApp()
frame = DragFrame()
app.SetTopWindow(frame)
frame.Show()
app.MainLoop()
Second program (drop):
import wx
class TextDropTarget(wx.TextDropTarget):
def __init__(self, obj):
wx.TextDropTarget.__init__(self)
self.obj = obj
def OnDropText(self, x, y, data):
self.obj.WriteText(data + '\n\n')
wx.MessageBox("Error", "Error", style = wx.ICON_ERROR)
class DropFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
text = wx.TextCtrl(self, wx.ID_ANY)
text.SetDropTarget(TextDropTarget(text))
app = wx.PySimpleApp()
frame = DropFrame()
app.SetTopWindow(frame)
frame.Show()
app.MainLoop()
When you run both programs, place windows in the centre of the screen (part of drop window is visible), then drag a node from drag window to drop window - target window displays message box which isn't visible, target window is hidden behind source window.
How to implement drag&drop that will focus on the second (target) window? I've tried adding window.Show(), window.SetFocus(), even using some functions of WinAPI (through win32gui). I think there should be some standard way of doing this. What am I missing?
You need to do anything you want int DragOver method of DropTarget e.g. there you can raise and set focus on your window
sample working code for target
import wx
class TextDropTarget(wx.TextDropTarget):
def __init__(self, obj, callback):
wx.TextDropTarget.__init__(self)
self.obj = obj
self._callback = callback
def OnDropText(self, x, y, data):
self.obj.WriteText(data + '\n\n')
wx.MessageBox("Error", "Error", style = wx.ICON_ERROR)
def OnDragOver(self, *args):
wx.CallAfter(self._callback)
return wx.TextDropTarget.OnDragOver(self, *args)
class DropFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
text = wx.TextCtrl(self, wx.ID_ANY)
text.SetDropTarget(TextDropTarget(text, self._callback))
def _callback(self):
self.Raise()
self.SetFocus()
app = wx.PySimpleApp()
frame = DropFrame()
app.SetTopWindow(frame)
frame.Show()
app.MainLoop()
Wouldn't this work?
class DropFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
text = wx.TextCtrl(self, wx.ID_ANY)
self.SetFocus() # Set's the focus to this window, allowing it to receive keyboard input.
text.SetDropTarget(TextDropTarget(text))
wx.Frame inherits from wx.Window, that has SetFocus(self).
I have just tested it and it works. Just moved SetFocus before SetDropTarget, as its a cleaner behavior.

Categories