有时,需要将一些程序是放置在工具栏上的,这就涉及到wxpython如何实现将程序放在任务栏上的方法了。
工具栏在一个面板上,通常位于屏幕右下角的一块区域,这些程序由一个小图标表示。
它们是一些特殊程序,设计用来完成某些特定任务。
常见的例子就是时钟、混音器以及语言切换程序等。
它们又被叫做小工具(applets)。
专题教程:wxpython中文教程
在 wxPython 中,有一个 wx.TaskbarIcon 类,用来创建这样的小工具程序,其构建器不接受任何参数。
wx.TaskbarIcon()
例子:
 
#!/usr/bin/python
#coding=utf-8
#mytaskbaricon.py
import wx
class MyTaskBarIcon(wx.TaskBarIcon):
    def __init__(self, frame):
        wx.TaskBarIcon.__init__(self)
        
        self.frame = frame
        self.SetIcon(wx.Icon('icons/web.png', wx.BITMAP_TYPE_PNG), 
                     'mytaskbaricon.py')
        self.Bind(wx.EVT_MENU, self.OnTaskBarActivate, id=1)
        self.Bind(wx.EVT_MENU, self.OnTaskBarDeactivate, id=2)
        self.Bind(wx.EVT_MENU, self.OnTaskBarClose, id=3)
    def CreatePopupMenu(self):
        menu = wx.Menu()
        menu.Append(1, '显 示')
        menu.Append(2, '隐 藏')
        menu.Append(3, '关 闭')
        return menu
    
    def OnTaskBarClose(self, event):
        self.frame.Close()
        
    def OnTaskBarActivate(self, event):
        if not self.frame.IsShown():
            self.frame.Show()
            
    def OnTaskBarDeactivate(self, event):
        if self.frame.IsShown():
            self.frame.Hide()
class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, 
                          (-1, -1), (290, 280))
        
        self.taskicon = MyTaskBarIcon(self)
        self.Center()
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        
    def OnClose(self, event):
        self.taskicon.Destroy()
        self.Destroy()      
      
class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'mytaskbaricon.py')
        frame.Show(True)
        self.SetTopWindow(frame)
        return True
    
app = MyApp(0)
app.MainLoop()
如图:
